diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..4aa168f73 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,95 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=lf + +# +## These files are binary and should be left untouched +# + +# (binary is a macro for -text -diff) +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.mov binary +*.mp4 binary +*.mp3 binary +*.flv binary +*.fla binary +*.swf binary +*.gz binary +*.zip binary +*.7z binary +*.ttf binary +*.eot binary +*.woff binary +*.pyc binary +*.pdf binary + +# source code +*.php text filter=spabs +*.css text filter=spabs +*.sass text filter=spabs +*.scss text filter=spabs +*.less text filter=spabs +*.styl text filter=spabs +*.js text filter=spabs +*.coffee text filter=spabs +*.json text filter=spabs +*.htm text filter=spabs +*.html text filter=spabs +*.xml text filter=spabs +*.svg text filter=spabs +*.txt text filter=spabs +*.ini text filter=spabs +*.inc text filter=spabs +*.pl text filter=spabs +*.rb text filter=spabs +*.py text filter=spabs +*.scm text filter=spabs +*.sql text filter=spabs +*.sh text filter=spabs +*.bat text filter=spabs + +# templates +*.ejs text filter=spabs +*.hbt text filter=spabs +*.jade text filter=spabs +*.haml text filter=spabs +*.hbs text filter=spabs +*.dot text filter=spabs +*.tmpl text filter=spabs +*.tpl text filter=spabs +*.phtml text filter=spabs + +# server config +.htaccess text filter=spabs + +# git config +.gitattributes text filter=spabs +.gitignore text filter=spabs +.gitconfig text filter=spabs + +# code analysis config +.jshintrc text filter=spabs +.jscsrc text filter=spabs +.jshintignore text filter=spabs +.csslintrc text filter=spabs + +# misc config +*.yaml text filter=spabs +*.yml text filter=spabs +.editorconfig text filter=spabs + +# build config +*.npmignore text filter=spabs +*.bowerrc text filter=spabs + +# Heroku +Procfile text filter=spabs +.slugignore text filter=spabs + +# Documentation +*.md text filter=spabs +LICENSE text filter=spabs +AUTHORS text filter=spabs diff --git a/.gitconfig b/.gitconfig new file mode 100644 index 000000000..db6645bc1 --- /dev/null +++ b/.gitconfig @@ -0,0 +1,6 @@ +[filter "spabs"] + clean = expand --initial -t 4 + smudge = expand --initial -t 4 + required +[merge] + renormalize = true \ No newline at end of file diff --git a/action.php b/action.php index e843b9cb1..7c66a2b5b 100644 --- a/action.php +++ b/action.php @@ -27,8 +27,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 * @depricated */ @@ -38,11 +38,11 @@ if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - // run controller or view and echo page content - echo $owa->handleRequestFromURL(); + // run controller or view and echo page content + echo $owa->handleRequestFromURL(); } else { - // unload owa - $owa->restInPeace(); + // unload owa + $owa->restInPeace(); } ?> \ No newline at end of file diff --git a/api.php b/api.php index 02091e889..26cf79572 100644 --- a/api.php +++ b/api.php @@ -27,9 +27,9 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 - * @link http://wiki.openwebanalytics.com/index.php?title=REST_API + * @version $Revision$ + * @since owa 1.3.0 + * @link http://wiki.openwebanalytics.com/index.php?title=REST_API */ // define entry point cnstant @@ -39,11 +39,11 @@ if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - // run api command and echo page content - echo $owa->handleRequest('', 'base.apiRequest'); + // run api command and echo page content + echo $owa->handleRequest('', 'base.apiRequest'); } else { - // unload owa - $owa->restInPeace(); + // unload owa + $owa->restInPeace(); } ?> \ No newline at end of file diff --git a/cli.php b/cli.php index 29311bbb6..bf2b2e64e 100755 --- a/cli.php +++ b/cli.php @@ -28,32 +28,32 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.2.1 + * @version $Revision$ + * @since owa 1.2.1 */ define('OWA_CLI', true); if (!empty($_POST)) { - exit(); + exit(); } elseif (!empty($_GET)) { - exit(); + exit(); } elseif (!empty($argv)) { - $params = array(); - // get params from the command line args - // $argv is a php super global variable - - for ($i=1; $iisEndpointEnabled( basename( __FILE__ ) ) ) { - // setting CLI mode to true - $owa->setSetting('base', 'cli_mode', true); - // setting user auth - $owa->setCurrentUser('admin', 'cli-user'); - // run controller or view and echo page content - $s = owa_coreAPI::serviceSingleton(); - $s->loadCliCommands(); - - if (array_key_exists('cmd', $params)) { - - $cmd = $s->getCliCommandClass($params['cmd']); - - if ($cmd) { - $params['do'] = $cmd; - echo $owa->handleRequest($params); - } else { - echo "Invalid command name."; - } - - } else { - echo "Missing a command argument."; - } + // setting CLI mode to true + $owa->setSetting('base', 'cli_mode', true); + // setting user auth + $owa->setCurrentUser('admin', 'cli-user'); + // run controller or view and echo page content + $s = owa_coreAPI::serviceSingleton(); + $s->loadCliCommands(); + + if (array_key_exists('cmd', $params)) { + + $cmd = $s->getCliCommandClass($params['cmd']); + + if ($cmd) { + $params['do'] = $cmd; + echo $owa->handleRequest($params); + } else { + echo "Invalid command name."; + } + + } else { + echo "Missing a command argument."; + } } else { - // unload owa - $owa->restInPeace(); + // unload owa + $owa->restInPeace(); } ?> \ No newline at end of file diff --git a/composer.json b/composer.json index 2eb9990f5..b7336f314 100644 --- a/composer.json +++ b/composer.json @@ -17,6 +17,6 @@ "require": { - "ua-parser/uap-php": "~3.9.7" + "ua-parser/uap-php": "~3.9.7" } } diff --git a/conf/country2Timezones.php b/conf/country2Timezones.php index a9f21a97a..9ff9f7698 100644 --- a/conf/country2Timezones.php +++ b/conf/country2Timezones.php @@ -1,790 +1,790 @@ array( - "AL" => "America/Chicago", - "AK" => "America/Anchorage", - "AZ" => "America/Phoenix", - "CA" => "America/Los_Angeles", - "CO" => "America/Denver", - "CT" => "America/New_York", - "HI" => "Pacific/Honolulu", - "IN" => "America/Indianapolis"), - - "CA" => array( - "AB" => "America/Edmonton", - "BC" => "America/Vancouver", - "MB" => "America/Winnipeg", - "NB" => "America/Halifax", - "NL" => "America/St_Johns", - "NT" => "America/Yellowknife", - "NU" => "America/Rankin_Inlet", - "ON" => "America/Rainy_River", - "QC" => "America/Montreal", - "SK" => "America/Regina", - "YT" => "America/Whitehorse"), - - "AU" => array( - "01" => "Australia/Canberra", - "02" => "Australia/NSW", - "03" => "Australia/North", - "04" => "Australia/Queensland", - "05" => "Australia/South", - "06" => "Australia/Tasmania", - "07" => "Australia/Victoria", - "08" => "Australia/West"), - - "AS" => array( - 0 => "US/Samoa"), - "CI" => array( - 0 => "Africa/Abidjan"), - "GH" => array( - 0 => "Africa/Accra"), - "DZ" => array( - 0 => "Africa/Algiers"), - "ER" => array( - 0 => "Africa/Asmera"), - "ML" => array( - 0 => "Africa/Bamako"), - "CF" => array( - 0 => "Africa/Bangui"), - "GM" => array( - 0 => "Africa/Banjul"), - "GW" => array( - 0 => "Africa/Bissau"), - "CG" => array( - 0 => "Africa/Brazzaville"), - "BI" => array( - 0 => "Africa/Bujumbura"), - "EG" => array( - 0 => "Africa/Cairo"), - "MA" => array( - 0 => "Africa/Casablanca"), - "GN" => array( - 0 => "Africa/Conakry"), - "SN" => array( - 0 => "Africa/Dakar"), - "DJ" => array( - 0 => "Africa/Djibouti"), - "SL" => array( - 0 => "Africa/Freetown"), - "BW" => array( - 0 => "Africa/Gaborone"), - "ZW" => array( - 0 => "Africa/Harare"), - "ZA" => array( - 0 => "Africa/Johannesburg"), - "UG" => array( - 0 => "Africa/Kampala"), - "SD" => array( - 0 => "Africa/Khartoum"), - "RW" => array( - 0 => "Africa/Kigali"), - "NG" => array( - 0 => "Africa/Lagos"), - "GA" => array( - 0 => "Africa/Libreville"), - "TG" => array( - 0 => "Africa/Lome"), - "AO" => array( - 0 => "Africa/Luanda"), - "ZM" => array( - 0 => "Africa/Lusaka"), - "GQ" => array( - 0 => "Africa/Malabo"), - "LS" => array( - 0 => "Africa/Maseru"), - "SZ" => array( - 0 => "Africa/Mbabane"), - "SO" => array( - 0 => "Africa/Mogadishu"), - "KE" => array( - 0 => "Africa/Nairobi"), - "TD" => array( - 0 => "Africa/Ndjamena"), - "MR" => array( - 0 => "Africa/Nouakchott"), - "BF" => array( - 0 => "Africa/Ouagadougou"), - "ST" => array( - 0 => "Africa/Sao_Tome"), - "LY" => array( - 0 => "Africa/Tripoli"), - "TN" => array( - 0 => "Africa/Tunis"), - "AI" => array( - 0 => "America/Anguilla"), - "AG" => array( - 0 => "America/Antigua"), - "AW" => array( - 0 => "America/Aruba"), - "BB" => array( - 0 => "America/Barbados"), - - "BZ" => array( - 0 => "America/Belize"), - - "CO" => array( + "US" => array( + "AL" => "America/Chicago", + "AK" => "America/Anchorage", + "AZ" => "America/Phoenix", + "CA" => "America/Los_Angeles", + "CO" => "America/Denver", + "CT" => "America/New_York", + "HI" => "Pacific/Honolulu", + "IN" => "America/Indianapolis"), + + "CA" => array( + "AB" => "America/Edmonton", + "BC" => "America/Vancouver", + "MB" => "America/Winnipeg", + "NB" => "America/Halifax", + "NL" => "America/St_Johns", + "NT" => "America/Yellowknife", + "NU" => "America/Rankin_Inlet", + "ON" => "America/Rainy_River", + "QC" => "America/Montreal", + "SK" => "America/Regina", + "YT" => "America/Whitehorse"), + + "AU" => array( + "01" => "Australia/Canberra", + "02" => "Australia/NSW", + "03" => "Australia/North", + "04" => "Australia/Queensland", + "05" => "Australia/South", + "06" => "Australia/Tasmania", + "07" => "Australia/Victoria", + "08" => "Australia/West"), + + "AS" => array( + 0 => "US/Samoa"), + "CI" => array( + 0 => "Africa/Abidjan"), + "GH" => array( + 0 => "Africa/Accra"), + "DZ" => array( + 0 => "Africa/Algiers"), + "ER" => array( + 0 => "Africa/Asmera"), + "ML" => array( + 0 => "Africa/Bamako"), + "CF" => array( + 0 => "Africa/Bangui"), + "GM" => array( + 0 => "Africa/Banjul"), + "GW" => array( + 0 => "Africa/Bissau"), + "CG" => array( + 0 => "Africa/Brazzaville"), + "BI" => array( + 0 => "Africa/Bujumbura"), + "EG" => array( + 0 => "Africa/Cairo"), + "MA" => array( + 0 => "Africa/Casablanca"), + "GN" => array( + 0 => "Africa/Conakry"), + "SN" => array( + 0 => "Africa/Dakar"), + "DJ" => array( + 0 => "Africa/Djibouti"), + "SL" => array( + 0 => "Africa/Freetown"), + "BW" => array( + 0 => "Africa/Gaborone"), + "ZW" => array( + 0 => "Africa/Harare"), + "ZA" => array( + 0 => "Africa/Johannesburg"), + "UG" => array( + 0 => "Africa/Kampala"), + "SD" => array( + 0 => "Africa/Khartoum"), + "RW" => array( + 0 => "Africa/Kigali"), + "NG" => array( + 0 => "Africa/Lagos"), + "GA" => array( + 0 => "Africa/Libreville"), + "TG" => array( + 0 => "Africa/Lome"), + "AO" => array( + 0 => "Africa/Luanda"), + "ZM" => array( + 0 => "Africa/Lusaka"), + "GQ" => array( + 0 => "Africa/Malabo"), + "LS" => array( + 0 => "Africa/Maseru"), + "SZ" => array( + 0 => "Africa/Mbabane"), + "SO" => array( + 0 => "Africa/Mogadishu"), + "KE" => array( + 0 => "Africa/Nairobi"), + "TD" => array( + 0 => "Africa/Ndjamena"), + "MR" => array( + 0 => "Africa/Nouakchott"), + "BF" => array( + 0 => "Africa/Ouagadougou"), + "ST" => array( + 0 => "Africa/Sao_Tome"), + "LY" => array( + 0 => "Africa/Tripoli"), + "TN" => array( + 0 => "Africa/Tunis"), + "AI" => array( + 0 => "America/Anguilla"), + "AG" => array( + 0 => "America/Antigua"), + "AW" => array( + 0 => "America/Aruba"), + "BB" => array( + 0 => "America/Barbados"), + + "BZ" => array( + 0 => "America/Belize"), + + "CO" => array( 0 => "America/Bogota"), - "VE" => array( + "VE" => array( 0 => "America/Caracas"), - "KY" => array( - 0 => "America/Cayman"), + "KY" => array( + 0 => "America/Cayman"), - "CR" => array( - 0 => "America/Costa_Rica"), + "CR" => array( + 0 => "America/Costa_Rica"), - "DM" => array( - 0 => "America/Dominica"), + "DM" => array( + 0 => "America/Dominica"), - "SV" => array( - 0 => "America/El_Salvador"), + "SV" => array( + 0 => "America/El_Salvador"), - "GD" => array( - 0 => "America/Grenada"), + "GD" => array( + 0 => "America/Grenada"), - "FR" => array( - 0 => "Europe/Paris"), + "FR" => array( + 0 => "Europe/Paris"), - "GP" => array( - 0 => "America/Guadeloupe"), + "GP" => array( + 0 => "America/Guadeloupe"), - "GT" => array( - 0 => "America/Guatemala"), + "GT" => array( + 0 => "America/Guatemala"), - "GY" => array( - 0 => "America/Guyana"), + "GY" => array( + 0 => "America/Guyana"), - "CU" => array( - 0 => "America/Havana"), + "CU" => array( + 0 => "America/Havana"), - "JM" => array( - 0 => "America/Jamaica"), + "JM" => array( + 0 => "America/Jamaica"), - "BO" => array( - 0 => "America/La_Paz"), + "BO" => array( + 0 => "America/La_Paz"), - "PE" => array( - 0 => "America/Lima"), + "PE" => array( + 0 => "America/Lima"), - "NI" => array( - 0 => "America/Managua"), + "NI" => array( + 0 => "America/Managua"), - "MQ" => array( - 0 => "America/Martinique"), + "MQ" => array( + 0 => "America/Martinique"), - "UY" => array( - 0 => "America/Montevideo"), + "UY" => array( + 0 => "America/Montevideo"), - "MS" => array( - 0 => "America/Montserrat"), + "MS" => array( + 0 => "America/Montserrat"), - "BS" => array( - 0 => "America/Nassau"), + "BS" => array( + 0 => "America/Nassau"), - "PA" => array( - 0 => "America/Panama"), + "PA" => array( + 0 => "America/Panama"), - "SR" => array( - 0 => "America/Paramaribo"), + "SR" => array( + 0 => "America/Paramaribo"), - "PR" => array( - 0 => "America/Puerto_Rico"), + "PR" => array( + 0 => "America/Puerto_Rico"), - "KN" => array( - 0 => "America/St_Kitts"), + "KN" => array( + 0 => "America/St_Kitts"), - "LC" => array( - 0 => "America/St_Lucia"), + "LC" => array( + 0 => "America/St_Lucia"), - "VC" => array( - 0 => "America/St_Vincent"), + "VC" => array( + 0 => "America/St_Vincent"), - "HN" => array( - 0 => "America/Tegucigalpa"), + "HN" => array( + 0 => "America/Tegucigalpa"), - "YE" => array( - 0 => "Asia/Aden"), + "YE" => array( + 0 => "Asia/Aden"), - "JO" => array( - 0 => "Asia/Amman"), + "JO" => array( + 0 => "Asia/Amman"), - "TM" => array( - 0 => "Asia/Ashgabat"), + "TM" => array( + 0 => "Asia/Ashgabat"), - "IQ" => array( - 0 => "Asia/Baghdad"), + "IQ" => array( + 0 => "Asia/Baghdad"), - "BH" => array( - 0 => "Asia/Bahrain"), + "BH" => array( + 0 => "Asia/Bahrain"), - "AZ" => array( - 0 => "Asia/Baku"), + "AZ" => array( + 0 => "Asia/Baku"), - "TH" => array( - 0 => "Asia/Bangkok"), + "TH" => array( + 0 => "Asia/Bangkok"), - "LB" => array( - 0 => "Asia/Beirut"), + "LB" => array( + 0 => "Asia/Beirut"), - "KG" => array( - 0 => "Asia/Bishkek"), + "KG" => array( + 0 => "Asia/Bishkek"), - "BN" => array( - 0 => "Asia/Brunei"), + "BN" => array( + 0 => "Asia/Brunei"), - "IN" => array( - 0 => "Asia/Calcutta"), + "IN" => array( + 0 => "Asia/Calcutta"), - "MN" => array( - 0 => "Asia/Choibalsan"), + "MN" => array( + 0 => "Asia/Choibalsan"), - "LK" => array( - 0 => "Asia/Colombo"), + "LK" => array( + 0 => "Asia/Colombo"), - "BD" => array( - 0 => "Asia/Dhaka"), + "BD" => array( + 0 => "Asia/Dhaka"), - "AE" => array( - 0 => "Asia/Dubai"), + "AE" => array( + 0 => "Asia/Dubai"), - "TJ" => array( - 0 => "Asia/Dushanbe"), + "TJ" => array( + 0 => "Asia/Dushanbe"), - "HK" => array( - 0 => "Asia/Hong_Kong"), + "HK" => array( + 0 => "Asia/Hong_Kong"), - "TR" => array( - 0 => "Asia/Istanbul"), + "TR" => array( + 0 => "Asia/Istanbul"), - "IL" => array( - 0 => "Asia/Jerusalem"), + "IL" => array( + 0 => "Asia/Jerusalem"), - "AF" => array( - 0 => "Asia/Kabul"), + "AF" => array( + 0 => "Asia/Kabul"), - "PK" => array( - 0 => "Asia/Karachi"), + "PK" => array( + 0 => "Asia/Karachi"), - "NP" => array( - 0 => "Asia/Katmandu"), + "NP" => array( + 0 => "Asia/Katmandu"), - "KW" => array( - 0 => "Asia/Kuwait"), + "KW" => array( + 0 => "Asia/Kuwait"), - "MO" => array( - 0 => "Asia/Macao"), + "MO" => array( + 0 => "Asia/Macao"), - "PH" => array( - 0 => "Asia/Manila"), + "PH" => array( + 0 => "Asia/Manila"), - "OM" => array( - 0 => "Asia/Muscat"), + "OM" => array( + 0 => "Asia/Muscat"), - "CY" => array( - 0 => "Asia/Nicosia"), + "CY" => array( + 0 => "Asia/Nicosia"), - "KP" => array( - 0 => "Asia/Pyongyang"), + "KP" => array( + 0 => "Asia/Pyongyang"), - "QA" => array( - 0 => "Asia/Qatar"), + "QA" => array( + 0 => "Asia/Qatar"), - "MM" => array( - 0 => "Asia/Rangoon"), + "MM" => array( + 0 => "Asia/Rangoon"), - "SA" => array( - 0 => "Asia/Riyadh"), + "SA" => array( + 0 => "Asia/Riyadh"), - "KR" => array( - 0 => "Asia/Seoul"), + "KR" => array( + 0 => "Asia/Seoul"), - "SG" => array( - 0 => "Asia/Singapore"), + "SG" => array( + 0 => "Asia/Singapore"), - "TW" => array( - 0 => "Asia/Taipei"), + "TW" => array( + 0 => "Asia/Taipei"), - "GE" => array( - 0 => "Asia/Tbilisi"), + "GE" => array( + 0 => "Asia/Tbilisi"), - "BT" => array( - 0 => "Asia/Thimphu"), + "BT" => array( + 0 => "Asia/Thimphu"), - "JP" => array( - 0 => "Asia/Tokyo"), + "JP" => array( + 0 => "Asia/Tokyo"), - "LA" => array( - 0 => "Asia/Vientiane"), + "LA" => array( + 0 => "Asia/Vientiane"), - "AM" => array( - 0 => "Asia/Yerevan"), + "AM" => array( + 0 => "Asia/Yerevan"), - "BM" => array( - 0 => "Atlantic/Bermuda"), + "BM" => array( + 0 => "Atlantic/Bermuda"), - "CV" => array( - 0 => "Atlantic/Cape_Verde"), + "CV" => array( + 0 => "Atlantic/Cape_Verde"), - "FO" => array( - 0 => "Atlantic/Faeroe"), + "FO" => array( + 0 => "Atlantic/Faeroe"), - "IS" => array( - 0 => "Atlantic/Reykjavik"), + "IS" => array( + 0 => "Atlantic/Reykjavik"), - "GS" => array( - 0 => "Atlantic/South_Georgia"), + "GS" => array( + 0 => "Atlantic/South_Georgia"), - "SH" => array( - 0 => "Atlantic/St_Helena"), + "SH" => array( + 0 => "Atlantic/St_Helena"), - "CL" => array( - 0 => "Chile/Continental"), + "CL" => array( + 0 => "Chile/Continental"), - "NL" => array( - 0 => "Europe/Amsterdam"), + "NL" => array( + 0 => "Europe/Amsterdam"), - "AD" => array( - 0 => "Europe/Andorra"), + "AD" => array( + 0 => "Europe/Andorra"), - "GR" => array( - 0 => "Europe/Athens"), + "GR" => array( + 0 => "Europe/Athens"), - "YU" => array( - 0 => "Europe/Belgrade"), + "YU" => array( + 0 => "Europe/Belgrade"), - "DE" => array( - 0 => "Europe/Berlin"), + "DE" => array( + 0 => "Europe/Berlin"), - "SK" => array( - 0 => "Europe/Bratislava"), + "SK" => array( + 0 => "Europe/Bratislava"), - "BE" => array( - 0 => "Europe/Brussels"), + "BE" => array( + 0 => "Europe/Brussels"), - "RO" => array( - 0 => "Europe/Bucharest"), + "RO" => array( + 0 => "Europe/Bucharest"), - "HU" => array( - 0 => "Europe/Budapest"), + "HU" => array( + 0 => "Europe/Budapest"), - "DK" => array( - 0 => "Europe/Copenhagen"), + "DK" => array( + 0 => "Europe/Copenhagen"), - "IE" => array( - 0 => "Europe/Dublin"), + "IE" => array( + 0 => "Europe/Dublin"), - "GI" => array( - 0 => "Europe/Gibraltar"), + "GI" => array( + 0 => "Europe/Gibraltar"), - "FI" => array( - 0 => "Europe/Helsinki"), + "FI" => array( + 0 => "Europe/Helsinki"), - "SI" => array( - 0 => "Europe/Ljubljana"), + "SI" => array( + 0 => "Europe/Ljubljana"), - "GB" => array( - 0 => "Europe/London"), + "GB" => array( + 0 => "Europe/London"), - "LU" => array( - 0 => "Europe/Luxembourg"), + "LU" => array( + 0 => "Europe/Luxembourg"), - "MT" => array( - 0 => "Europe/Malta"), + "MT" => array( + 0 => "Europe/Malta"), - "BY" => array( - 0 => "Europe/Minsk"), + "BY" => array( + 0 => "Europe/Minsk"), - "MC" => array( - 0 => "Europe/Monaco"), + "MC" => array( + 0 => "Europe/Monaco"), - "NO" => array( - 0 => "Europe/Oslo"), + "NO" => array( + 0 => "Europe/Oslo"), - "CZ" => array( - 0 => "Europe/Prague"), + "CZ" => array( + 0 => "Europe/Prague"), - "LV" => array( - 0 => "Europe/Riga"), + "LV" => array( + 0 => "Europe/Riga"), - "IT" => array( - 0 => "Europe/Rome"), + "IT" => array( + 0 => "Europe/Rome"), - "SM" => array( - 0 => "Europe/San_Marino"), + "SM" => array( + 0 => "Europe/San_Marino"), - "BA" => array( - 0 => "Europe/Sarajevo"), + "BA" => array( + 0 => "Europe/Sarajevo"), - "MK" => array( - 0 => "Europe/Skopje"), + "MK" => array( + 0 => "Europe/Skopje"), - "BG" => array( - 0 => "Europe/Sofia"), + "BG" => array( + 0 => "Europe/Sofia"), - "SE" => array( - 0 => "Europe/Stockholm"), + "SE" => array( + 0 => "Europe/Stockholm"), - "EE" => array( - 0 => "Europe/Tallinn"), + "EE" => array( + 0 => "Europe/Tallinn"), - "AL" => array( - 0 => "Europe/Tirane"), + "AL" => array( + 0 => "Europe/Tirane"), - "LI" => array( - 0 => "Europe/Vaduz"), + "LI" => array( + 0 => "Europe/Vaduz"), - "VA" => array( - 0 => "Europe/Vatican"), + "VA" => array( + 0 => "Europe/Vatican"), - "AT" => array( - 0 => "Europe/Vienna"), + "AT" => array( + 0 => "Europe/Vienna"), - "LT" => array( - 0 => "Europe/Vilnius"), + "LT" => array( + 0 => "Europe/Vilnius"), - "PL" => array( - 0 => "Europe/Warsaw"), + "PL" => array( + 0 => "Europe/Warsaw"), - "HR" => array( - 0 => "Europe/Zagreb"), + "HR" => array( + 0 => "Europe/Zagreb"), - "IR" => array( - 0 => "Asia/Tehran"), + "IR" => array( + 0 => "Asia/Tehran"), - "MG" => array( - 0 => "Indian/Antananarivo"), + "MG" => array( + 0 => "Indian/Antananarivo"), - "CX" => array( - 0 => "Indian/Christmas"), + "CX" => array( + 0 => "Indian/Christmas"), - "CC" => array( - 0 => "Indian/Cocos"), + "CC" => array( + 0 => "Indian/Cocos"), - "KM" => array( - 0 => "Indian/Comoro"), + "KM" => array( + 0 => "Indian/Comoro"), - "MV" => array( - 0 => "Indian/Maldives"), + "MV" => array( + 0 => "Indian/Maldives"), - "MU" => array( - 0 => "Indian/Mauritius"), + "MU" => array( + 0 => "Indian/Mauritius"), - "YT" => array( - 0 => "Indian/Mayotte"), + "YT" => array( + 0 => "Indian/Mayotte"), - "RE" => array( - 0 => "Indian/Reunion"), + "RE" => array( + 0 => "Indian/Reunion"), - "FJ" => array( - 0 => "Pacific/Fiji"), + "FJ" => array( + 0 => "Pacific/Fiji"), - "TV" => array( - 0 => "Pacific/Funafuti"), + "TV" => array( + 0 => "Pacific/Funafuti"), - "GU" => array( - 0 => "Pacific/Guam"), + "GU" => array( + 0 => "Pacific/Guam"), - "NR" => array( - 0 => "Pacific/Nauru"), + "NR" => array( + 0 => "Pacific/Nauru"), - "NU" => array( - 0 => "Pacific/Niue"), + "NU" => array( + 0 => "Pacific/Niue"), - "NF" => array( - 0 => "Pacific/Norfolk"), + "NF" => array( + 0 => "Pacific/Norfolk"), - "PW" => array( - 0 => "Pacific/Palau"), + "PW" => array( + 0 => "Pacific/Palau"), - "PN" => array( - 0 => "Pacific/Pitcairn"), + "PN" => array( + 0 => "Pacific/Pitcairn"), - "CK" => array( - 0 => "Pacific/Rarotonga"), + "CK" => array( + 0 => "Pacific/Rarotonga"), - "WS" => array( - 0 => "Pacific/Samoa"), + "WS" => array( + 0 => "Pacific/Samoa"), - "KI" => array( - 0 => "Pacific/Tarawa"), + "KI" => array( + 0 => "Pacific/Tarawa"), - "TO" => array( - 0 => "Pacific/Tongatapu"), + "TO" => array( + 0 => "Pacific/Tongatapu"), - "WF" => array( - 0 => "Pacific/Wallis"), + "WF" => array( + 0 => "Pacific/Wallis"), - "TZ" => array( - 0 => "Africa/Dar_es_Salaam"), + "TZ" => array( + 0 => "Africa/Dar_es_Salaam"), - "VN" => array( - 0 => "Asia/Phnom_Penh"), + "VN" => array( + 0 => "Asia/Phnom_Penh"), - "KH" => array( - 0 => "Asia/Phnom_Penh"), + "KH" => array( + 0 => "Asia/Phnom_Penh"), - "CM" => array( - 0 => "Africa/Lagos"), + "CM" => array( + 0 => "Africa/Lagos"), - "DO" => array( - 0 => "America/Santo_Domingo"), + "DO" => array( + 0 => "America/Santo_Domingo"), - "ET" => array( - 0 => "Africa/Addis_Ababa"), + "ET" => array( + 0 => "Africa/Addis_Ababa"), - "FX" => array( - 0 => "Europe/Paris"), - - "HT" => array( - 0 => "America/Port-au-Prince"), + "FX" => array( + 0 => "Europe/Paris"), + + "HT" => array( + 0 => "America/Port-au-Prince"), - "CH" => array( - 0 => "Europe/Zurich"), + "CH" => array( + 0 => "Europe/Zurich"), - "AN" => array( - 0 => "America/Curacao"), + "AN" => array( + 0 => "America/Curacao"), - "BJ" => array( - 0 => "Africa/Porto-Novo"), + "BJ" => array( + 0 => "Africa/Porto-Novo"), - "EH" => array( - 0 => "Africa/El_Aaiun"), + "EH" => array( + 0 => "Africa/El_Aaiun"), - "FK" => array( - 0 => "Atlantic/Stanley"), + "FK" => array( + 0 => "Atlantic/Stanley"), - "GF" => array( - 0 => "America/Cayenne"), + "GF" => array( + 0 => "America/Cayenne"), - "IO" => array( - 0 => "Indian/Chagos"), + "IO" => array( + 0 => "Indian/Chagos"), - "MD" => array( - 0 => "Europe/Chisinau"), + "MD" => array( + 0 => "Europe/Chisinau"), - "MP" => array( - 0 => "Pacific/Saipan"), + "MP" => array( + 0 => "Pacific/Saipan"), - "MW" => array( - 0 => "Africa/Blantyre"), + "MW" => array( + 0 => "Africa/Blantyre"), - "NA" => array( - 0 => "Africa/Windhoek"), + "NA" => array( + 0 => "Africa/Windhoek"), - "NC" => array( - 0 => "Pacific/Noumea"), + "NC" => array( + 0 => "Pacific/Noumea"), - "PG" => array( - 0 => "Pacific/Port_Moresby"), + "PG" => array( + 0 => "Pacific/Port_Moresby"), - "PM" => array( - 0 => "America/Miquelon"), + "PM" => array( + 0 => "America/Miquelon"), - "PS" => array( - 0 => "Asia/Gaza"), + "PS" => array( + 0 => "Asia/Gaza"), - "PY" => array( - 0 => "America/Asuncion"), + "PY" => array( + 0 => "America/Asuncion"), - "SB" => array( - 0 => "Pacific/Guadalcanal"), + "SB" => array( + 0 => "Pacific/Guadalcanal"), - "SC" => array( - 0 => "Indian/Mahe"), + "SC" => array( + 0 => "Indian/Mahe"), - "SJ" => array( - 0 => "Arctic/Longyearbyen"), + "SJ" => array( + 0 => "Arctic/Longyearbyen"), - "SY" => array( - 0 => "Asia/Damascus"), + "SY" => array( + 0 => "Asia/Damascus"), - "TC" => array( - 0 => "America/Grand_Turk"), + "TC" => array( + 0 => "America/Grand_Turk"), - "TF" => array( - 0 => "Indian/Kerguelen"), + "TF" => array( + 0 => "Indian/Kerguelen"), - "TK" => array( - 0 => "Pacific/Fakaofo"), + "TK" => array( + 0 => "Pacific/Fakaofo"), - "TT" => array( - 0 => "America/Port_of_Spain"), + "TT" => array( + 0 => "America/Port_of_Spain"), - "VG" => array( - 0 => "America/Tortola"), + "VG" => array( + 0 => "America/Tortola"), - "VI" => array( - 0 => "America/St_Thomas"), + "VI" => array( + 0 => "America/St_Thomas"), - "VU" => array( - 0 => "Pacific/Efate"), + "VU" => array( + 0 => "Pacific/Efate"), - "RS" => array( - 0 => "Europe/Belgrade"), + "RS" => array( + 0 => "Europe/Belgrade"), - "ME" => array( - 0 => "Europe/Podgorica"), + "ME" => array( + 0 => "Europe/Podgorica"), - "AX" => array( - 0 => "Europe/Mariehamn"), + "AX" => array( + 0 => "Europe/Mariehamn"), - "IM" => array( - 0 => "Europe/Isle_of_Man"), + "IM" => array( + 0 => "Europe/Isle_of_Man"), - "JE" => array( - 0 => "Europe/Jersey"), + "JE" => array( + 0 => "Europe/Jersey"), - "MF" => array( - 0 => "America/Marigot"), + "MF" => array( + 0 => "America/Marigot"), - "AR" => array( - "01" => "America/Argentina/Buenos_Aires", - "02" => "America/Argentina/Catamarca", - "03" => "America/Argentina/Tucuman", - "04" => "America/Argentina/Rio_Gallegos", - "05" => "America/Argentina/Cordoba", - "10" => "America/Argentina/Jujuy", - "11" => "America/Argentina/San_Luis", - "12" => "America/Argentina/La_Rioja", - "13" => "America/Argentina/Mendoza", - "17" => "America/Argentina/Salta", - "18" => "America/Argentina/San_Juan", - "23" => "America/Argentina/Ushuaia"), + "AR" => array( + "01" => "America/Argentina/Buenos_Aires", + "02" => "America/Argentina/Catamarca", + "03" => "America/Argentina/Tucuman", + "04" => "America/Argentina/Rio_Gallegos", + "05" => "America/Argentina/Cordoba", + "10" => "America/Argentina/Jujuy", + "11" => "America/Argentina/San_Luis", + "12" => "America/Argentina/La_Rioja", + "13" => "America/Argentina/Mendoza", + "17" => "America/Argentina/Salta", + "18" => "America/Argentina/San_Juan", + "23" => "America/Argentina/Ushuaia"), - "BR" => array( - - "01" => "America/Rio_Branco", - "02" => "America/Maceio", - "03" => "America/Sao_Paulo", - "04" => "America/Manaus", - "05" => "America/Bahia", - "06" => "America/Fortaleza", - "11" => "America/Campo_Grande", - "13" => "America/Belem", - "14" => "America/Cuiaba", - "17" => "America/Recife", - "24" => "America/Porto_Velho", - "25" => "America/Boa_Vista", - "28" => "America/Maceio", - "31" => "America/Araguaina"), + "BR" => array( + + "01" => "America/Rio_Branco", + "02" => "America/Maceio", + "03" => "America/Sao_Paulo", + "04" => "America/Manaus", + "05" => "America/Bahia", + "06" => "America/Fortaleza", + "11" => "America/Campo_Grande", + "13" => "America/Belem", + "14" => "America/Cuiaba", + "17" => "America/Recife", + "24" => "America/Porto_Velho", + "25" => "America/Boa_Vista", + "28" => "America/Maceio", + "31" => "America/Araguaina"), - "CD" => array( - - "02" => "Africa/Kinshasa", - "05" => "Africa/Lubumbashi", - "06" => "Africa/Kinshasa", - "08" => "Africa/Kinshasa", - "10" => "Africa/Lubumbashi", - "11" => "Africa/Lubumbashi", - "12" => "Africa/Lubumbashi"), + "CD" => array( + + "02" => "Africa/Kinshasa", + "05" => "Africa/Lubumbashi", + "06" => "Africa/Kinshasa", + "08" => "Africa/Kinshasa", + "10" => "Africa/Lubumbashi", + "11" => "Africa/Lubumbashi", + "12" => "Africa/Lubumbashi"), - "CN" => array( + "CN" => array( - "01" => "Asia/Shanghai", - "05" => "Asia/Harbin", - "06" => "Asia/Chongqing", - "13" => "Asia/Urumqi"), + "01" => "Asia/Shanghai", + "05" => "Asia/Harbin", + "06" => "Asia/Chongqing", + "13" => "Asia/Urumqi"), - "EC" => array( + "EC" => array( + + "01" => "Pacific/Galapagos", + "02" => "America/Guayaquil"), - "01" => "Pacific/Galapagos", - "02" => "America/Guayaquil"), - - "ES" => array( - "07" => "Europe/Madrid", - "51" => "Africa/Ceuta", - "53" => "Atlantic/Canary"), + "ES" => array( + "07" => "Europe/Madrid", + "51" => "Africa/Ceuta", + "53" => "Atlantic/Canary"), - "GL" => array( + "GL" => array( - "01" => "America/Thule", - "02" => "America/Godthab"), + "01" => "America/Thule", + "02" => "America/Godthab"), - "ID" => array( + "ID" => array( - "01" => "Asia/Pontianak", - "02" => "Asia/Makassar", - "03" => "Asia/Jakarta", - "09" => "Asia/Jayapura"), + "01" => "Asia/Pontianak", + "02" => "Asia/Makassar", + "03" => "Asia/Jakarta", + "09" => "Asia/Jayapura"), - "KZ" => array( + "KZ" => array( - "01" => "Asia/Almaty", - "03" => "Asia/Qyzylorda", - "04" => "Asia/Aqtobe", - "05" => "Asia/Qyzylorda", - "06" => "Asia/Aqtau", - "07" => "Asia/Oral", - "08" => "Asia/Qyzylorda"), + "01" => "Asia/Almaty", + "03" => "Asia/Qyzylorda", + "04" => "Asia/Aqtobe", + "05" => "Asia/Qyzylorda", + "06" => "Asia/Aqtau", + "07" => "Asia/Oral", + "08" => "Asia/Qyzylorda"), - "MX" => array( + "MX" => array( - "01" => "America/Mexico_City", - "02" => "America/Tijuana", - "03" => "America/Hermosillo", - "04" => "America/Merida", - "06" => "America/Chihuahua", - "07" => "America/Monterrey", - "10" => "America/Mazatlan", - "23" => "America/Cancun"), - - "MY" => array( + "01" => "America/Mexico_City", + "02" => "America/Tijuana", + "03" => "America/Hermosillo", + "04" => "America/Merida", + "06" => "America/Chihuahua", + "07" => "America/Monterrey", + "10" => "America/Mazatlan", + "23" => "America/Cancun"), + + "MY" => array( - "01" => "Asia/Kuala_Lumpur", - "11" => "Asia/Kuching"), + "01" => "Asia/Kuala_Lumpur", + "11" => "Asia/Kuching"), - "NZ" => array( + "NZ" => array( - "85" => "Pacific/Auckland", - "F7" => "Pacific/Chatham"), + "85" => "Pacific/Auckland", + "F7" => "Pacific/Chatham"), - "PT" => array( + "PT" => array( - "02" => "Europe/Lisbon", + "02" => "Europe/Lisbon", "10" => "Atlantic/Madeira"), - "RU" => array( - - "01" => "Europe/Volgograd", - "02" => "Asia/Irkutsk", - "03" => "Asia/Novokuznetsk", - "05" => "Asia/Vladivostok", - "06" => "Europe/Moscow", - "08" => "Europe/Samara", - "09" => "Europe/Moscow", - "13" => "Asia/Yekaterinburg", - "15" => "Asia/Anadyr", - "18" => "Asia/Krasnoyarsk", - "23" => "Europe/Kaliningrad", - "26" => "Asia/Kamchatka", - "31" => "Asia/Krasnoyarsk", - "32" => "Asia/Omsk", - "35" => "Asia/Yekaterinburg", - "44" => "Asia/Magadan", - "53" => "Asia/Novosibirsk", - "63" => "Asia/Yakutsk", - "64" => "Asia/Sakhalin"), + "RU" => array( + + "01" => "Europe/Volgograd", + "02" => "Asia/Irkutsk", + "03" => "Asia/Novokuznetsk", + "05" => "Asia/Vladivostok", + "06" => "Europe/Moscow", + "08" => "Europe/Samara", + "09" => "Europe/Moscow", + "13" => "Asia/Yekaterinburg", + "15" => "Asia/Anadyr", + "18" => "Asia/Krasnoyarsk", + "23" => "Europe/Kaliningrad", + "26" => "Asia/Kamchatka", + "31" => "Asia/Krasnoyarsk", + "32" => "Asia/Omsk", + "35" => "Asia/Yekaterinburg", + "44" => "Asia/Magadan", + "53" => "Asia/Novosibirsk", + "63" => "Asia/Yakutsk", + "64" => "Asia/Sakhalin"), - "UA" => array( + "UA" => array( - "01" => "Europe/Kiev", - "03" => "Europe/Uzhgorod", - "04" => "Europe/Zaporozhye", - "08" => "Europe/Simferopol", - "09" => "Europe/Kiev"), + "01" => "Europe/Kiev", + "03" => "Europe/Uzhgorod", + "04" => "Europe/Zaporozhye", + "08" => "Europe/Simferopol", + "09" => "Europe/Kiev"), - "UZ" => array( - "01" => "Asia/Tashkent", - "02" => "Asia/Samarkand", - "03" => "Asia/Tashkent"), + "UZ" => array( + "01" => "Asia/Tashkent", + "02" => "Asia/Samarkand", + "03" => "Asia/Tashkent"), - "TL" => array( - 0 => "Asia/Dili"), + "TL" => array( + 0 => "Asia/Dili"), - "PF" => array( - 0 => "Pacific/Marquesas") + "PF" => array( + 0 => "Pacific/Marquesas") ); ?> \ No newline at end of file diff --git a/conf/countryNames2Codes.php b/conf/countryNames2Codes.php index 57adcdc20..8ec489f0a 100644 --- a/conf/countryNames2Codes.php +++ b/conf/countryNames2Codes.php @@ -1,250 +1,250 @@ 'AF', - "Åland islands" => 'AX', - "albania" => 'AL', - "algeria" => 'DZ', - "american samoa" => 'AS', - "andorra" => 'AD', - "angola" => 'AO', - "anguilla" => 'AI', - "antarctica" => 'AQ', - "antigua and barbuda" => 'AG', - "argentina" => 'AR', - "armenia" => 'AM', - "aruba" => 'AW', - "australia" => 'AU', - "austria" => 'AT', - "azerbaijan" => 'AZ', - "bahamas" => 'BS', - "bahrain" => 'BH', - "bangladesh" => 'BD', - "barbados" => 'BB', - "belarus" => 'BY', - "belgium" => 'BE', - "belize" => 'BZ', - "benin" => 'BJ', - "bermuda" => 'BM', - "bhutan" => 'BT', - "bolivia, plurinational state of" => 'BO', - "bosnia and herzegovina" => 'BA', - "botswana" => 'BW', - "bouvet island" => 'BV', - "brazil" => 'BR', - "british indian ocean territory" => 'IO', - "brunei darussalam" => 'BN', - "bulgaria" => 'BG', - "burkina faso" => 'BF', - "burundi" => 'BI', - "cambodia" => 'KH', - "cameroon" => 'CM', - "canada" => 'CA', - "cape verde" => 'CV', - "cayman islands" => 'KY', - "central african republic" => 'CF', - "chad" => 'TD', - "chile" => 'CL', - "china" => 'CN', - "christmas island" => 'CX', - "cocos (keeling) islands" => 'CC', - "colombia" => 'CO', - "comoros" => 'KM', - "congo" => 'CG', - "congo, the democratic republic of the" => 'CD', - "cook islands" => 'CK', - "costa rica" => 'CR', - "côte d'ivoire" => 'CI', - "croatia" => 'HR', - "cuba" => 'CU', - "cyprus" => 'CY', - "czech republic" => 'CZ', - "denmark" => 'DK', - "djibouti" => 'DJ', - "dominica" => 'DM', - "dominican republic" => 'DO', - "ecuador" => 'EC', - "egypt" => 'EG', - "el salvador" => 'SV', - "equatorial guinea" => 'GQ', - "eritrea" => 'ER', - "estonia" => 'EE', - "ethiopia" => 'ET', - "falkland islands (malvinas)" => 'FK', - "faroe islands" => 'FO', - "fiji" => 'FJ', - "finland" => 'FI', - "france" => 'FR', - "french guiana" => 'GF', - "french polynesia" => 'PF', - "french southern territories" => 'TF', - "gabon" => 'GA', - "gambia" => 'GM', - "georgia" => 'GE', - "germany" => 'DE', - "ghana" => 'GH', - "gibraltar" => 'GI', - "greece" => 'GR', - "greenland" => 'GL', - "grenada" => 'GD', - "guadeloupe" => 'GP', - "guam" => 'GU', - "guatemala" => 'GT', - "guernsey" => 'GG', - "guinea" => 'GN', - "guinea-bissau" => 'GW', - "guyana" => 'GY', - "haiti" => 'HT', - "heard island and mcdonald islands" => 'HM', - "holy see (vatican city state)" => 'VA', - "honduras" => 'HN', - "hong kong" => 'HK', - "hungary" => 'HU', - "iceland" => 'IS', - "india" => 'IN', - "indonesia" => 'ID', - "iran, islamic republic of" => 'IR', - "iraq" => 'IQ', - "ireland" => 'IE', - "isle of man" => 'IM', - "israel" => 'IL', - "italy" => 'IT', - "jamaica" => 'JM', - "japan" => 'JP', - "jersey" => 'JE', - "jordan" => 'JO', - "kazakhstan" => 'KZ', - "kenya" => 'KE', - "kiribati" => 'KI', - "korea, democratic people's republic of" => 'KP', - "korea, republic of" => 'KR', - "kuwait" => 'KW', - "kyrgyzstan" => 'KG', - "lao people's democratic republic" => 'LA', - "latvia" => 'LV', - "lebanon" => 'LB', - "lesotho" => 'LS', - "liberia" => 'LR', - "libyan arab jamahiriya" => 'LY', - "liechtenstein" => 'LI', - "lithuania" => 'LT', - "luxembourg" => 'LU', - "macao" => 'MO', - "macedonia, the former yugoslav republic of" => 'MK', - "madagascar" => 'MG', - "malawi" => 'MW', - "malaysia" => 'MY', - "maldives" => 'MV', - "mali" => 'ML', - "malta" => 'MT', - "marshall islands" => 'MH', - "martinique" => 'MQ', - "mauritania" => 'MR', - "mauritius" => 'MU', - "mayotte" => 'YT', - "mexico" => 'MX', - "micronesia, federated states of" => 'FM', - "moldova, republic of" => 'MD', - "monaco" => 'MC', - "mongolia" => 'MN', - "montenegro" => 'ME', - "montserrat" => 'MS', - "morocco" => 'MA', - "mozambique" => 'MZ', - "myanmar" => 'MM', - "namibia" => 'NA', - "nauru" => 'NR', - "nepal" => 'NP', - "netherlands" => 'NL', - "netherlands antilles" => 'AN', - "new caledonia" => 'NC', - "new zealand" => 'NZ', - "nicaragua" => 'NI', - "niger" => 'NE', - "nigeria" => 'NG', - "niue" => 'NU', - "norfolk island" => 'NF', - "northern mariana islands" => 'MP', - "norway" => 'NO', - "oman" => 'OM', - "pakistan" => 'PK', - "palau" => 'PW', - "palestinian territory, occupied" => 'PS', - "panama" => 'PA', - "papua new guinea" => 'PG', - "paraguay" => 'PY', - "peru" => 'PE', - "philippines" => 'PH', - "pitcairn" => 'PN', - "poland" => 'PL', - "portugal" => 'PT', - "puerto rico" => 'PR', - "qatar" => 'QA', - "réunion" => 'RE', - "romania" => 'RO', - "russian federation" => 'RU', - "rwanda" => 'RW', - "saint barthélemy" => 'BL', - "saint helena" => 'SH', - "saint kitts and nevis" => 'KN', - "saint lucia" => 'LC', - "saint martin (french part)" => 'MF', - "saint pierre and miquelon" => 'PM', - "saint vincent and the grenadines" => 'VC', - "samoa" => 'WS', - "san marino" => 'SM', - "sao tome and principe" => 'ST', - "saudi arabia" => 'SA', - "senegal" => 'SN', - "serbia" => 'RS', - "seychelles" => 'SC', - "sierra leone" => 'SL', - "singapore" => 'SG', - "slovakia" => 'SK', - "slovenia" => 'SI', - "solomon islands" => 'SB', - "somalia" => 'SO', - "south africa" => 'ZA', - "south georgia and the south sandwich islands" => 'GS', - "spain" => 'ES', - "sri lanka" => 'LK', - "sudan" => 'SD', - "suriname" => 'SR', - "svalbard and jan mayen" => 'SJ', - "swaziland" => 'SZ', - "sweden" => 'SE', - "switzerland" => 'CH', - "syrian arab republic" => 'SY', - "taiwan, province of china" => 'TW', - "tajikistan" => 'TJ', - "tanzania, united republic of" => 'TZ', - "thailand" => 'TH', - "timor-leste" => 'TL', - "togo" => 'TG', - "tokelau" => 'TK', - "tonga" => 'TO', - "trinidad and tobago" => 'TT', - "tunisia" => 'TN', - "turkey" => 'TR', - "turkmenistan" => 'TM', - "turks and caicos islands" => 'TC', - "tuvalu" => 'TV', - "uganda" => 'UG', - "ukraine" => 'UA', - "united arab emirates" => 'AE', - "united kingdom" => 'GB', - "united states" => 'US', - "united states minor outlying islands" => 'UM', - "uruguay" => 'UY', - "uzbekistan" => 'UZ', - "vanuatu" => 'VU', - "venezuela, bolivarian republic of" => 'VE', - "viet nam" => 'VN', - "virgin islands, british" => 'VG', - "virgin islands, u.s." => 'VI', - "wallis and futuna" => 'WF', - "western sahara" => 'EH', - "yemen" => 'YE', - "zambia" => 'ZM', - "zimbabwe" => 'ZW', + "afghanistan" => 'AF', + "Åland islands" => 'AX', + "albania" => 'AL', + "algeria" => 'DZ', + "american samoa" => 'AS', + "andorra" => 'AD', + "angola" => 'AO', + "anguilla" => 'AI', + "antarctica" => 'AQ', + "antigua and barbuda" => 'AG', + "argentina" => 'AR', + "armenia" => 'AM', + "aruba" => 'AW', + "australia" => 'AU', + "austria" => 'AT', + "azerbaijan" => 'AZ', + "bahamas" => 'BS', + "bahrain" => 'BH', + "bangladesh" => 'BD', + "barbados" => 'BB', + "belarus" => 'BY', + "belgium" => 'BE', + "belize" => 'BZ', + "benin" => 'BJ', + "bermuda" => 'BM', + "bhutan" => 'BT', + "bolivia, plurinational state of" => 'BO', + "bosnia and herzegovina" => 'BA', + "botswana" => 'BW', + "bouvet island" => 'BV', + "brazil" => 'BR', + "british indian ocean territory" => 'IO', + "brunei darussalam" => 'BN', + "bulgaria" => 'BG', + "burkina faso" => 'BF', + "burundi" => 'BI', + "cambodia" => 'KH', + "cameroon" => 'CM', + "canada" => 'CA', + "cape verde" => 'CV', + "cayman islands" => 'KY', + "central african republic" => 'CF', + "chad" => 'TD', + "chile" => 'CL', + "china" => 'CN', + "christmas island" => 'CX', + "cocos (keeling) islands" => 'CC', + "colombia" => 'CO', + "comoros" => 'KM', + "congo" => 'CG', + "congo, the democratic republic of the" => 'CD', + "cook islands" => 'CK', + "costa rica" => 'CR', + "côte d'ivoire" => 'CI', + "croatia" => 'HR', + "cuba" => 'CU', + "cyprus" => 'CY', + "czech republic" => 'CZ', + "denmark" => 'DK', + "djibouti" => 'DJ', + "dominica" => 'DM', + "dominican republic" => 'DO', + "ecuador" => 'EC', + "egypt" => 'EG', + "el salvador" => 'SV', + "equatorial guinea" => 'GQ', + "eritrea" => 'ER', + "estonia" => 'EE', + "ethiopia" => 'ET', + "falkland islands (malvinas)" => 'FK', + "faroe islands" => 'FO', + "fiji" => 'FJ', + "finland" => 'FI', + "france" => 'FR', + "french guiana" => 'GF', + "french polynesia" => 'PF', + "french southern territories" => 'TF', + "gabon" => 'GA', + "gambia" => 'GM', + "georgia" => 'GE', + "germany" => 'DE', + "ghana" => 'GH', + "gibraltar" => 'GI', + "greece" => 'GR', + "greenland" => 'GL', + "grenada" => 'GD', + "guadeloupe" => 'GP', + "guam" => 'GU', + "guatemala" => 'GT', + "guernsey" => 'GG', + "guinea" => 'GN', + "guinea-bissau" => 'GW', + "guyana" => 'GY', + "haiti" => 'HT', + "heard island and mcdonald islands" => 'HM', + "holy see (vatican city state)" => 'VA', + "honduras" => 'HN', + "hong kong" => 'HK', + "hungary" => 'HU', + "iceland" => 'IS', + "india" => 'IN', + "indonesia" => 'ID', + "iran, islamic republic of" => 'IR', + "iraq" => 'IQ', + "ireland" => 'IE', + "isle of man" => 'IM', + "israel" => 'IL', + "italy" => 'IT', + "jamaica" => 'JM', + "japan" => 'JP', + "jersey" => 'JE', + "jordan" => 'JO', + "kazakhstan" => 'KZ', + "kenya" => 'KE', + "kiribati" => 'KI', + "korea, democratic people's republic of" => 'KP', + "korea, republic of" => 'KR', + "kuwait" => 'KW', + "kyrgyzstan" => 'KG', + "lao people's democratic republic" => 'LA', + "latvia" => 'LV', + "lebanon" => 'LB', + "lesotho" => 'LS', + "liberia" => 'LR', + "libyan arab jamahiriya" => 'LY', + "liechtenstein" => 'LI', + "lithuania" => 'LT', + "luxembourg" => 'LU', + "macao" => 'MO', + "macedonia, the former yugoslav republic of" => 'MK', + "madagascar" => 'MG', + "malawi" => 'MW', + "malaysia" => 'MY', + "maldives" => 'MV', + "mali" => 'ML', + "malta" => 'MT', + "marshall islands" => 'MH', + "martinique" => 'MQ', + "mauritania" => 'MR', + "mauritius" => 'MU', + "mayotte" => 'YT', + "mexico" => 'MX', + "micronesia, federated states of" => 'FM', + "moldova, republic of" => 'MD', + "monaco" => 'MC', + "mongolia" => 'MN', + "montenegro" => 'ME', + "montserrat" => 'MS', + "morocco" => 'MA', + "mozambique" => 'MZ', + "myanmar" => 'MM', + "namibia" => 'NA', + "nauru" => 'NR', + "nepal" => 'NP', + "netherlands" => 'NL', + "netherlands antilles" => 'AN', + "new caledonia" => 'NC', + "new zealand" => 'NZ', + "nicaragua" => 'NI', + "niger" => 'NE', + "nigeria" => 'NG', + "niue" => 'NU', + "norfolk island" => 'NF', + "northern mariana islands" => 'MP', + "norway" => 'NO', + "oman" => 'OM', + "pakistan" => 'PK', + "palau" => 'PW', + "palestinian territory, occupied" => 'PS', + "panama" => 'PA', + "papua new guinea" => 'PG', + "paraguay" => 'PY', + "peru" => 'PE', + "philippines" => 'PH', + "pitcairn" => 'PN', + "poland" => 'PL', + "portugal" => 'PT', + "puerto rico" => 'PR', + "qatar" => 'QA', + "réunion" => 'RE', + "romania" => 'RO', + "russian federation" => 'RU', + "rwanda" => 'RW', + "saint barthélemy" => 'BL', + "saint helena" => 'SH', + "saint kitts and nevis" => 'KN', + "saint lucia" => 'LC', + "saint martin (french part)" => 'MF', + "saint pierre and miquelon" => 'PM', + "saint vincent and the grenadines" => 'VC', + "samoa" => 'WS', + "san marino" => 'SM', + "sao tome and principe" => 'ST', + "saudi arabia" => 'SA', + "senegal" => 'SN', + "serbia" => 'RS', + "seychelles" => 'SC', + "sierra leone" => 'SL', + "singapore" => 'SG', + "slovakia" => 'SK', + "slovenia" => 'SI', + "solomon islands" => 'SB', + "somalia" => 'SO', + "south africa" => 'ZA', + "south georgia and the south sandwich islands" => 'GS', + "spain" => 'ES', + "sri lanka" => 'LK', + "sudan" => 'SD', + "suriname" => 'SR', + "svalbard and jan mayen" => 'SJ', + "swaziland" => 'SZ', + "sweden" => 'SE', + "switzerland" => 'CH', + "syrian arab republic" => 'SY', + "taiwan, province of china" => 'TW', + "tajikistan" => 'TJ', + "tanzania, united republic of" => 'TZ', + "thailand" => 'TH', + "timor-leste" => 'TL', + "togo" => 'TG', + "tokelau" => 'TK', + "tonga" => 'TO', + "trinidad and tobago" => 'TT', + "tunisia" => 'TN', + "turkey" => 'TR', + "turkmenistan" => 'TM', + "turks and caicos islands" => 'TC', + "tuvalu" => 'TV', + "uganda" => 'UG', + "ukraine" => 'UA', + "united arab emirates" => 'AE', + "united kingdom" => 'GB', + "united states" => 'US', + "united states minor outlying islands" => 'UM', + "uruguay" => 'UY', + "uzbekistan" => 'UZ', + "vanuatu" => 'VU', + "venezuela, bolivarian republic of" => 'VE', + "viet nam" => 'VN', + "virgin islands, british" => 'VG', + "virgin islands, u.s." => 'VI', + "wallis and futuna" => 'WF', + "western sahara" => 'EH', + "yemen" => 'YE', + "zambia" => 'ZM', + "zimbabwe" => 'ZW', ); ?> \ No newline at end of file diff --git a/conf/os.ini b/conf/os.ini index da0d0d814..8516f7762 100644 --- a/conf/os.ini +++ b/conf/os.ini @@ -65,7 +65,7 @@ name="UNIX [unknown]" [Mac_PowerPC] name="Mac OS [PowerPC]" - + [Mac OS X] name="Mac OS X" diff --git a/conf/query_strings.ini b/conf/query_strings.ini index 7da711d4b..e98e4e631 100644 --- a/conf/query_strings.ini +++ b/conf/query_strings.ini @@ -1,29 +1,29 @@ -[\?(?:.+&|)q=(.+?)(?:&|$)] -[search\?(?:.+&|)p=(.+?)(?:&|$)] -[\?(?:.+&|)Keywords=(.+?)(?:&|$)] -[\?(?:.+&|)MT=(.+?)(?:&|$)] -[\?(?:.+&|)Q=(.+?)(?:&|$)] -[\?(?:.+&|)QUERY=(.+?)(?:&|$)] -[\?(?:.+&|)Suchwort=(.+?)(?:&|$)] -[\?(?:.+&|)ask=(.+?)(?:&|$)] -[\?(?:.+&|)eingabe=(.+?)(?:&|$)] -[\?(?:.+&|)in=(.+?)(?:&|$)] -[\?(?:.+&|)keyword=(.+?)(?:&|$)] -[\?(?:.+&|)keywords=(.+?)(?:&|$)] -[\?(?:.+&|)kw=(.+?)(?:&|$)] -[\?(?:.+&|)mots=(.+?)(?:&|$)] -[\?(?:.+&|)motscles=(.+?)(?:&|$)] -[\?(?:.+&|)query=(.+?)(?:&|$)] -[\?(?:.+&|)query2=(.+?)(?:&|$)] -[\?(?:.+&|)queryterm=(.+?)(?:&|$)] -[\?(?:.+&|)sTerm=(.+?)(?:&|$)] -[\?(?:.+&|)sc=(.+?)(?:&|$)] -[\?(?:.+&|)search=(.+?)(?:&|$)] -[\?(?:.+&|)search2=(.+?)(?:&|$)] -[\?(?:.+&|)searchfor=(.+?)(?:&|$)] -[\?(?:.+&|)searchText=(.+?)(?:&|$)] -[\?(?:.+&|)srch=(.+?)(?:&|$)] -[\?(?:.+&|)su=(.+?)(?:&|$)] -[\?(?:.+&|)such=(.+?)(?:&|$)] -[\?(?:.+&|)suche=(.+?)(?:&|$)] +[\?(?:.+&|)q=(.+?)(?:&|$)] +[search\?(?:.+&|)p=(.+?)(?:&|$)] +[\?(?:.+&|)Keywords=(.+?)(?:&|$)] +[\?(?:.+&|)MT=(.+?)(?:&|$)] +[\?(?:.+&|)Q=(.+?)(?:&|$)] +[\?(?:.+&|)QUERY=(.+?)(?:&|$)] +[\?(?:.+&|)Suchwort=(.+?)(?:&|$)] +[\?(?:.+&|)ask=(.+?)(?:&|$)] +[\?(?:.+&|)eingabe=(.+?)(?:&|$)] +[\?(?:.+&|)in=(.+?)(?:&|$)] +[\?(?:.+&|)keyword=(.+?)(?:&|$)] +[\?(?:.+&|)keywords=(.+?)(?:&|$)] +[\?(?:.+&|)kw=(.+?)(?:&|$)] +[\?(?:.+&|)mots=(.+?)(?:&|$)] +[\?(?:.+&|)motscles=(.+?)(?:&|$)] +[\?(?:.+&|)query=(.+?)(?:&|$)] +[\?(?:.+&|)query2=(.+?)(?:&|$)] +[\?(?:.+&|)queryterm=(.+?)(?:&|$)] +[\?(?:.+&|)sTerm=(.+?)(?:&|$)] +[\?(?:.+&|)sc=(.+?)(?:&|$)] +[\?(?:.+&|)search=(.+?)(?:&|$)] +[\?(?:.+&|)search2=(.+?)(?:&|$)] +[\?(?:.+&|)searchfor=(.+?)(?:&|$)] +[\?(?:.+&|)searchText=(.+?)(?:&|$)] +[\?(?:.+&|)srch=(.+?)(?:&|$)] +[\?(?:.+&|)su=(.+?)(?:&|$)] +[\?(?:.+&|)such=(.+?)(?:&|$)] +[\?(?:.+&|)suche=(.+?)(?:&|$)] [\?(?:.+&|)szukaj=(.+?)(?:&|$)] \ No newline at end of file diff --git a/conf/search_engines.ini b/conf/search_engines.ini index 8e70aa377..47528b179 100644 --- a/conf/search_engines.ini +++ b/conf/search_engines.ini @@ -1,417 +1,417 @@ -;;; Search Engines - -[info] -name="2006-02-22" - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Google -[Google] -name="Google" - -[google\.co\.uk/custom\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[groups\.google\.(?:com|fr)/groups\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[go(?:[ogle]{4})\.[a-z.]+(?::80|)/(?:search|linux|de|ie|url|custom|cobrand|bsd|mac|netscape|uk|redhat|webhp)\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[google\.com/u/[A-Za-z0-9]*\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[images\.google\.[a-z]*/imgres\?(?:.+&|)imgurl=(.+?)(?:&|$)] -parent=Google - -[images\.google\.[a-z]*/images\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[google\.netscape\.com/(?:netscape|search)\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[216\.239\.[0-9]+\.100/search\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[free\.fr/google\.pl\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Google - -[google\.com/search\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Google - -[google\.netscape\.com/netscape\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Google - -[google\.com/netscape\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Google - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; OVERTURE - -[Overture] -name="Overture" - -[overture\.com/d/search[^?]*\?(?:.+&|)Keywords=(.+?)(?:&|$)] -parent=Overture - -[search\.as\.orientation\.com/cgi-bin/gotosearch\.cgi\?(?:.+&|)Keywords=(.+?)(?:&|$)] -parent=Overture - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; HOTBOT - -[Hotbot] -name="HotBot" - -[hotbot\?(?:.+&|)MT=(.+?)(?:&|$)] -parent=Hotbot - -[hotbot\.lycos\.com/?\?(?:.+&|)MT=(.+?)(?:&|$)] -parent=Hotbot - -[hotbot\.lycos\.com\/text/default\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] -parent=Hotbot - -[hotbot\.lycos\.com/director\.asp\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Hotbot - -[hotbot\.lycos\.com/include/nc_frameset_ink_highend\.asp\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Hotbot - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MSN - -[MSN] -name="MSN search" - -[search\..*msn\..+/spbasic\.htm\?(?:.+&|)MT=(.+?)(?:&|$)] -parent=MSN - -[search\..*msn\..+/(?:sp)?results\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] -parent=MSN - -[search\.[a-z.]*msn\.[a-z.]+/(?:sp)?(?:results\.asp|basic\.htm|results\.aspx)\?(?:.+&|)q=(.+?)(?:&|$)] -parent=MSN - -[search\.[a-z.]*msn\.[a-z.]+/autosearch/as_(?:pane)?results\.asp\?(?:.+&|)q=(.+?)(?:&|$)] -parent=MSN - -[msn\.[^/]+/[^?]+?default\.asp\?(?:.+&|)s=(.+?)(?:&|$)] -parent=MSN - -[encarta\.msn\.com/(?:encarta|find)/search\.asp\?(?:.+&|)search=(.+?)(?:&|$)] -name="MSN Encarta" - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Random Engines - -[goo\.ne\.jp/[^?]+\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] -name="Goo Japan" - -[search\.icq\.com/default\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] -name="ICQ Directory" - -[nomade\.(?:tiscali\.)?fr/(?:ink|[_a-zA-Z0-9]*recherche[_a-zA-Z0-9]*)\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] -name="Nomade" - -[yahoo\.co\.jp/bin/search\?(?:.+&|)p=(.+?)(?:&|$)] -name="Yahoo Japan" - -[metacrawler\.com(?:/crawler|)\?(?:.+&|)general=(.+?)(?:&|$)] -name="MetaCrawler" - -[chello\.[^/]+/utilities/search[^?]*\?(?:.+&|)keywords=(.+?)(?:&|$)] -name="Chello" - -[Voila] -name"Viola" - -[voila\.[^/]+/(?:S/)?(?:ns|www|msie_fr|quiquoiou|voilang|voila|search|wanadoo[a-z_]*|r?msie4[a-z_]*)\?(?:.+&|)kw=(.+?)(?:&|$)] -parent=Voila - -[voila\.fr/voila\?(?:.+&|)kw=(.+?)(?:&|$)] -parent=Voila - -[voila\.fr/(?:quiquoiou|voilang|voila|search|wanadoo[a-z_]*|r?msie4[a-z_]*)/?\?(?:.+&|)mots=(.+?)(?:&|$)] -parent=Voila - -[search\.ke\.wanadoo\.fr/S/wanadoo\?(?:.+&|)kw=(.+?)(?:&|$)] -name="Wanadoo.fr" - -[freshmeat\.net/search/?\?(?:.+&|)q=(.+?)(?:&|$)] -name="Freshmeat" - -[Vivisimo] -name="Vivisimo" - -[vivisimo.com/search\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Vivisimo - -[vivisimo\.com/cgi-bin/xml2html\.sh\?(?:.+&|)s=(.+?)(?:&|$)] -parent=Vivisimo - -[vivisimo\.com/cgi-bin/treeHtmlMain\?(?:.+&|)s=(.+?)(?:&|$)] -parent=Vivisimo - -[webcrawler.com/cgi-bin/WebQuery\?(?:.+&|)searchText=(.+?)(?:&|$)] -name="WebCrawler" - -[findology\.com/(?:ce/|)search\.pl\?(?:.+&|)search=(.+?)(?:&|$)] -name="Findology" - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Search.com - -[Search.com] -name="Search.com" - -[search\.cnet\.com/Infoseek/\?(?:.+&|)QUERY=(.+?)(?:&|$)] -parent=Search.com - -[search\.com/Infoseek/\?(?:.+&|)QUERY=(.+?)(?:&|$)] -parent=Search.com - -[search\.com/search\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Search.com - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Ask Jeeves - -[Ask_Jeeves] -name="Ask Jeeves" - - -[(?:askjeeves|aj|ask)\..+/main/meta[aA]nswer\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -[(?:askjeeves|aj|ask)\..+/main/[aA]sk[jJ]eeves\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -[(?:askjeeves|aj|ask)\..+/main/followup\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -[(?:askjeeves|aj|ask)\..+/main/Links\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -[(?:askjeeves|aj|ask)\..+/main/moreResults\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -[tm\.ask\.com/r\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -[ask\.co\.uk/main/followup40\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] -parent=Ask_Jeeves - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LookSmart - -[Looksmart] -name="Looksmart" - -[looksmart\.com\?(?:.+&|)key=(.+?)(?:&|$)] -parent=Looksmart - -[looksmart\.(?:co\.uk|com)/r_search\?(?:.+&|)key=(.+?)(?:&|$)] -parent=Looksmart - -[surfy\.com/cgi-bin/search\?(?:.+&|)key=(.+?)(?:&|$)] -parent=Looksmart - -[synd(?:-[a-z]+)?\.looksmart\.co\.uk/synd-[a-z]*/Search[a-z]*\.jsp\?(?:.+&|)key=(.+?)(?:&|$)] -parent=Looksmart - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Alltheweb - -[alltheweb\.(?:com|net)/search\?(?:.+&|)q=(.+?)(?:&|$)] -name="Alltheweb" - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; AltaVista - -[Altavista] -name="AltaVista" - -[altavista\.com/(?:query|q|)\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.com/iepane\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.com/sites/search/res_text\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.com/sites/listings/GT_av\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.com/web\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.com/iepane\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.com/sites/search/res_text\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Altavista - -[altavista\.digital\.com/sites/search/web\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Altavista - -[[-a-z]+\.altavista\.com/q\?(?:.+&|)what=(.+?)(?:&|$)] -parent=Altavista - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CompuServe - -[CompuServe] -name="Compuserve" - -[compuserve(?:office)*\.de/suche/suche\.jsp\?(?:.+&|)q=(.+?)(?:&|$)] -parent=CompuServe - -[cissearch\.compuserve\.com/search/cssearch/cssearch-(?:frameset|results)\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] -parent=CompuServe - -[search\.cs\.com/search/cssearch/cssearch-frameset\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] -parent=CompuServe - -[websearch\.cs\.com/cs/results/cssearch-(?:banner|frameset)\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] -parent=CompuServe - -[websearch\.cs\.com/gateway/results/gateway-(?:cat|frameset|results|banner)\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] -parent=CompuServe - -[search\.compuserve\.co\.uk/results\.adp\?(?:.+&|)query=(.+?)(?:&|$)] -parent=CompuServe - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Dogpile - -[Dogpile] -name="Dogpile" - -[dogpile\.com/texis/search\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Dogpile - -[dogpile\.com/info.dogpl/search/web/(?:.+&|)] -parent=Dogpile - -[catalog\.dogpile\.com/texis/catalog\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Dogpile - -[catalog\.dogpile\.com/texis/redir/main\.bin\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Dogpile - -[opendir\.dogpile\.com/texis/dpdir/search\.html\?(?:.+&|)q=(.+?)(?:&|$)] -parent=Dogpile - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; AOL - -[AOL] -name="AOL" - -[(?:search|suchen|recherche|aolrecherches)\.aol\.(?:co\.)?[a-z.]+/(?:search|minisearch|itemsearch|results|web|cat|dirsearch|advncd|redirect)(?:_[a-z]+)?\.adp\?(?:.+&|)query=(.+?)(?:&|$)] -parent=AOL - -[uk-nf01\.web\.aol\.com/cgi-bin/pursuit\?(?:.+&|)query=(.+?)(?:&|$)] -parent=AOL - -[americaonline\.com\.br/cgi-bin\?(?:.+&|)query=(.+?)(?:&|$)] -parent=AOL - -[shopping\.aol\.de/scripts/ao/results\.php\?(?:.+&|)query=(.+?)(?:&|$)] -parent=AOL - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LYCOS - -[Lycos] -name="Lycos" - -[(?:richmedia|multimedia|search)\.lycos\.com/default.asp\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -[lycosuk\.co\.uk/cgi-bin/pursuit\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -[lycos\.com(?:\.)*/srch(?:/setup\.html|/more\.html)*\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -[search\.lycos\.com/main(?:/|/default.asp|)\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -[lycos\.com/srch/\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -[lycos\.com/srch/index\.html\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -[search\.lycos\.com/main\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Lycos - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MAMA - -[Mamma] -name="Mamma" - -[mamma\.com/Mamma\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Mamma - -[mamma[0-9]+\.mamma\.com/Mamma\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Mamma - -[partners\.mamma\.com/(?:Altavista|Askjeeves1|Beaucoup|Botbot|Cb_12c4|HotSheet|Hotbar|Pages)\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Mamma - -[mamma\.com/Mamma_pictures\?(?:.+&|)query=(.+?)(?:&|$)] -parent=Mamma - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; EXCITE - -[Excite] -name="Excite" - -[search\.excite\.com\?(?:.+&|)s=(.+?)(?:&|$)] -parent=Excite - -[excite\.[a-z.]+/search\search.dcg\?(?:.+&|)s=(.+?)(?:&|$)] -parent=Excite - -[\.excite(?:\.[a-z]+|)\.[a-z]+/[^?]+\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Excite - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; YAHOO - -[Yahoo] -name="Yahoo!" - -[de\.finance\.yahoo\.com/q\?(?:.+&|)s=(.+?)(?:&|$)] -parent=Yahoo - -[(?:[a-z]+\.)?search\.yahoo\.[^/]+/(?:[a-z]+/)?search/?[^?]*\?(?:.+&|)p=(.+?)(?:&|$)] -parent=Yahoo - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DMOZ - -[dmoz] -name="The Open Directory Project (DMOZ)" - -[search\.dmoz\.org\?(?:.+&|)search=(.+?)(?:&|$)] -parent=dmoz - -[directory\.wwwresources\.com/directory.cgi\?(?:.+&|)search2=(.+?)(?:&|$)] -parent=dmoz - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; NETSCAPE - -[Netscape] -name="Netscape" - -[(?:search|search-intl|directory)\.netscape\.com/(?:[a-z]*/)?google\.tmpl\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Netscape - -[search\.netscape\.com/search.psp\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Netscape - -[search\.netscape\.com\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Netscape - -[directory\.netscape\.com/cgi-bin/search\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Netscape - -[directory\.netscape\.com/search\.tmpl\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Netscape - -[search-intl\.netscape\.com/(?:de|fr|uk)/search(?:[0-9]|)\.tmpl\?(?:.+&|)search=(.+?)(?:&|$)] -parent=Netscape - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Default - -;;; [*] -;;; name="Unknown Referer" +;;; Search Engines + +[info] +name="2006-02-22" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Google +[Google] +name="Google" + +[google\.co\.uk/custom\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[groups\.google\.(?:com|fr)/groups\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[go(?:[ogle]{4})\.[a-z.]+(?::80|)/(?:search|linux|de|ie|url|custom|cobrand|bsd|mac|netscape|uk|redhat|webhp)\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[google\.com/u/[A-Za-z0-9]*\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[images\.google\.[a-z]*/imgres\?(?:.+&|)imgurl=(.+?)(?:&|$)] +parent=Google + +[images\.google\.[a-z]*/images\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[google\.netscape\.com/(?:netscape|search)\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[216\.239\.[0-9]+\.100/search\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[free\.fr/google\.pl\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Google + +[google\.com/search\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Google + +[google\.netscape\.com/netscape\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Google + +[google\.com/netscape\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Google + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; OVERTURE + +[Overture] +name="Overture" + +[overture\.com/d/search[^?]*\?(?:.+&|)Keywords=(.+?)(?:&|$)] +parent=Overture + +[search\.as\.orientation\.com/cgi-bin/gotosearch\.cgi\?(?:.+&|)Keywords=(.+?)(?:&|$)] +parent=Overture + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; HOTBOT + +[Hotbot] +name="HotBot" + +[hotbot\?(?:.+&|)MT=(.+?)(?:&|$)] +parent=Hotbot + +[hotbot\.lycos\.com/?\?(?:.+&|)MT=(.+?)(?:&|$)] +parent=Hotbot + +[hotbot\.lycos\.com\/text/default\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] +parent=Hotbot + +[hotbot\.lycos\.com/director\.asp\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Hotbot + +[hotbot\.lycos\.com/include/nc_frameset_ink_highend\.asp\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Hotbot + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MSN + +[MSN] +name="MSN search" + +[search\..*msn\..+/spbasic\.htm\?(?:.+&|)MT=(.+?)(?:&|$)] +parent=MSN + +[search\..*msn\..+/(?:sp)?results\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] +parent=MSN + +[search\.[a-z.]*msn\.[a-z.]+/(?:sp)?(?:results\.asp|basic\.htm|results\.aspx)\?(?:.+&|)q=(.+?)(?:&|$)] +parent=MSN + +[search\.[a-z.]*msn\.[a-z.]+/autosearch/as_(?:pane)?results\.asp\?(?:.+&|)q=(.+?)(?:&|$)] +parent=MSN + +[msn\.[^/]+/[^?]+?default\.asp\?(?:.+&|)s=(.+?)(?:&|$)] +parent=MSN + +[encarta\.msn\.com/(?:encarta|find)/search\.asp\?(?:.+&|)search=(.+?)(?:&|$)] +name="MSN Encarta" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Random Engines + +[goo\.ne\.jp/[^?]+\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] +name="Goo Japan" + +[search\.icq\.com/default\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] +name="ICQ Directory" + +[nomade\.(?:tiscali\.)?fr/(?:ink|[_a-zA-Z0-9]*recherche[_a-zA-Z0-9]*)\.asp\?(?:.+&|)MT=(.+?)(?:&|$)] +name="Nomade" + +[yahoo\.co\.jp/bin/search\?(?:.+&|)p=(.+?)(?:&|$)] +name="Yahoo Japan" + +[metacrawler\.com(?:/crawler|)\?(?:.+&|)general=(.+?)(?:&|$)] +name="MetaCrawler" + +[chello\.[^/]+/utilities/search[^?]*\?(?:.+&|)keywords=(.+?)(?:&|$)] +name="Chello" + +[Voila] +name"Viola" + +[voila\.[^/]+/(?:S/)?(?:ns|www|msie_fr|quiquoiou|voilang|voila|search|wanadoo[a-z_]*|r?msie4[a-z_]*)\?(?:.+&|)kw=(.+?)(?:&|$)] +parent=Voila + +[voila\.fr/voila\?(?:.+&|)kw=(.+?)(?:&|$)] +parent=Voila + +[voila\.fr/(?:quiquoiou|voilang|voila|search|wanadoo[a-z_]*|r?msie4[a-z_]*)/?\?(?:.+&|)mots=(.+?)(?:&|$)] +parent=Voila + +[search\.ke\.wanadoo\.fr/S/wanadoo\?(?:.+&|)kw=(.+?)(?:&|$)] +name="Wanadoo.fr" + +[freshmeat\.net/search/?\?(?:.+&|)q=(.+?)(?:&|$)] +name="Freshmeat" + +[Vivisimo] +name="Vivisimo" + +[vivisimo.com/search\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Vivisimo + +[vivisimo\.com/cgi-bin/xml2html\.sh\?(?:.+&|)s=(.+?)(?:&|$)] +parent=Vivisimo + +[vivisimo\.com/cgi-bin/treeHtmlMain\?(?:.+&|)s=(.+?)(?:&|$)] +parent=Vivisimo + +[webcrawler.com/cgi-bin/WebQuery\?(?:.+&|)searchText=(.+?)(?:&|$)] +name="WebCrawler" + +[findology\.com/(?:ce/|)search\.pl\?(?:.+&|)search=(.+?)(?:&|$)] +name="Findology" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Search.com + +[Search.com] +name="Search.com" + +[search\.cnet\.com/Infoseek/\?(?:.+&|)QUERY=(.+?)(?:&|$)] +parent=Search.com + +[search\.com/Infoseek/\?(?:.+&|)QUERY=(.+?)(?:&|$)] +parent=Search.com + +[search\.com/search\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Search.com + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Ask Jeeves + +[Ask_Jeeves] +name="Ask Jeeves" + + +[(?:askjeeves|aj|ask)\..+/main/meta[aA]nswer\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +[(?:askjeeves|aj|ask)\..+/main/[aA]sk[jJ]eeves\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +[(?:askjeeves|aj|ask)\..+/main/followup\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +[(?:askjeeves|aj|ask)\..+/main/Links\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +[(?:askjeeves|aj|ask)\..+/main/moreResults\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +[tm\.ask\.com/r\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +[ask\.co\.uk/main/followup40\.asp\?(?:.+&|)ask=(.+?)(?:&|$)] +parent=Ask_Jeeves + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LookSmart + +[Looksmart] +name="Looksmart" + +[looksmart\.com\?(?:.+&|)key=(.+?)(?:&|$)] +parent=Looksmart + +[looksmart\.(?:co\.uk|com)/r_search\?(?:.+&|)key=(.+?)(?:&|$)] +parent=Looksmart + +[surfy\.com/cgi-bin/search\?(?:.+&|)key=(.+?)(?:&|$)] +parent=Looksmart + +[synd(?:-[a-z]+)?\.looksmart\.co\.uk/synd-[a-z]*/Search[a-z]*\.jsp\?(?:.+&|)key=(.+?)(?:&|$)] +parent=Looksmart + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Alltheweb + +[alltheweb\.(?:com|net)/search\?(?:.+&|)q=(.+?)(?:&|$)] +name="Alltheweb" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; AltaVista + +[Altavista] +name="AltaVista" + +[altavista\.com/(?:query|q|)\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.com/iepane\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.com/sites/search/res_text\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.com/sites/listings/GT_av\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.com/web\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.com/iepane\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.com/sites/search/res_text\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Altavista + +[altavista\.digital\.com/sites/search/web\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Altavista + +[[-a-z]+\.altavista\.com/q\?(?:.+&|)what=(.+?)(?:&|$)] +parent=Altavista + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CompuServe + +[CompuServe] +name="Compuserve" + +[compuserve(?:office)*\.de/suche/suche\.jsp\?(?:.+&|)q=(.+?)(?:&|$)] +parent=CompuServe + +[cissearch\.compuserve\.com/search/cssearch/cssearch-(?:frameset|results)\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] +parent=CompuServe + +[search\.cs\.com/search/cssearch/cssearch-frameset\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] +parent=CompuServe + +[websearch\.cs\.com/cs/results/cssearch-(?:banner|frameset)\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] +parent=CompuServe + +[websearch\.cs\.com/gateway/results/gateway-(?:cat|frameset|results|banner)\.adp\?(?:.+&|)sTerm=(.+?)(?:&|$)] +parent=CompuServe + +[search\.compuserve\.co\.uk/results\.adp\?(?:.+&|)query=(.+?)(?:&|$)] +parent=CompuServe + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Dogpile + +[Dogpile] +name="Dogpile" + +[dogpile\.com/texis/search\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Dogpile + +[dogpile\.com/info.dogpl/search/web/(?:.+&|)] +parent=Dogpile + +[catalog\.dogpile\.com/texis/catalog\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Dogpile + +[catalog\.dogpile\.com/texis/redir/main\.bin\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Dogpile + +[opendir\.dogpile\.com/texis/dpdir/search\.html\?(?:.+&|)q=(.+?)(?:&|$)] +parent=Dogpile + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; AOL + +[AOL] +name="AOL" + +[(?:search|suchen|recherche|aolrecherches)\.aol\.(?:co\.)?[a-z.]+/(?:search|minisearch|itemsearch|results|web|cat|dirsearch|advncd|redirect)(?:_[a-z]+)?\.adp\?(?:.+&|)query=(.+?)(?:&|$)] +parent=AOL + +[uk-nf01\.web\.aol\.com/cgi-bin/pursuit\?(?:.+&|)query=(.+?)(?:&|$)] +parent=AOL + +[americaonline\.com\.br/cgi-bin\?(?:.+&|)query=(.+?)(?:&|$)] +parent=AOL + +[shopping\.aol\.de/scripts/ao/results\.php\?(?:.+&|)query=(.+?)(?:&|$)] +parent=AOL + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LYCOS + +[Lycos] +name="Lycos" + +[(?:richmedia|multimedia|search)\.lycos\.com/default.asp\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +[lycosuk\.co\.uk/cgi-bin/pursuit\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +[lycos\.com(?:\.)*/srch(?:/setup\.html|/more\.html)*\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +[search\.lycos\.com/main(?:/|/default.asp|)\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +[lycos\.com/srch/\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +[lycos\.com/srch/index\.html\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +[search\.lycos\.com/main\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Lycos + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MAMA + +[Mamma] +name="Mamma" + +[mamma\.com/Mamma\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Mamma + +[mamma[0-9]+\.mamma\.com/Mamma\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Mamma + +[partners\.mamma\.com/(?:Altavista|Askjeeves1|Beaucoup|Botbot|Cb_12c4|HotSheet|Hotbar|Pages)\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Mamma + +[mamma\.com/Mamma_pictures\?(?:.+&|)query=(.+?)(?:&|$)] +parent=Mamma + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; EXCITE + +[Excite] +name="Excite" + +[search\.excite\.com\?(?:.+&|)s=(.+?)(?:&|$)] +parent=Excite + +[excite\.[a-z.]+/search\search.dcg\?(?:.+&|)s=(.+?)(?:&|$)] +parent=Excite + +[\.excite(?:\.[a-z]+|)\.[a-z]+/[^?]+\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Excite + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; YAHOO + +[Yahoo] +name="Yahoo!" + +[de\.finance\.yahoo\.com/q\?(?:.+&|)s=(.+?)(?:&|$)] +parent=Yahoo + +[(?:[a-z]+\.)?search\.yahoo\.[^/]+/(?:[a-z]+/)?search/?[^?]*\?(?:.+&|)p=(.+?)(?:&|$)] +parent=Yahoo + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DMOZ + +[dmoz] +name="The Open Directory Project (DMOZ)" + +[search\.dmoz\.org\?(?:.+&|)search=(.+?)(?:&|$)] +parent=dmoz + +[directory\.wwwresources\.com/directory.cgi\?(?:.+&|)search2=(.+?)(?:&|$)] +parent=dmoz + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; NETSCAPE + +[Netscape] +name="Netscape" + +[(?:search|search-intl|directory)\.netscape\.com/(?:[a-z]*/)?google\.tmpl\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Netscape + +[search\.netscape\.com/search.psp\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Netscape + +[search\.netscape\.com\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Netscape + +[directory\.netscape\.com/cgi-bin/search\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Netscape + +[directory\.netscape\.com/search\.tmpl\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Netscape + +[search-intl\.netscape\.com/(?:de|fr|uk)/search(?:[0-9]|)\.tmpl\?(?:.+&|)search=(.+?)(?:&|$)] +parent=Netscape + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Default + +;;; [*] +;;; name="Unknown Referer" diff --git a/daemon.php b/daemon.php index 83ce55aa0..3822dc024 100644 --- a/daemon.php +++ b/daemon.php @@ -23,8 +23,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ require_once('owa_env.php'); require_once(OWA_DIR.'owa_php.php'); @@ -33,21 +33,21 @@ define('OWA_DAEMON', true); if (!empty($_POST)) { - exit(); + exit(); } elseif (!empty($_GET)) { - exit(); + exit(); } $owa = new owa_php(); if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - // start daemon - $daemon = new owa_daemon(); - $daemon->start(); - + // start daemon + $daemon = new owa_daemon(); + $daemon->start(); + } else { - // unload owa - $owa->restInPeace(); + // unload owa + $owa->restInPeace(); } ?> \ No newline at end of file diff --git a/includes/CronParser.php b/includes/CronParser.php index 53da2fc4a..d87095010 100644 --- a/includes/CronParser.php +++ b/includes/CronParser.php @@ -50,555 +50,555 @@ class CronParser { - var $bits = Array(); //exploded String like 0 1 * * * - var $now = Array(); //Array of cron-style entries for time() - var $lastRan; //Timestamp of last ran time. - var $taken; - var $debug; - var $year; - var $month; - var $day; - var $hour; - var $minute; - var $minutes_arr = array(); //minutes array based on cron string - var $hours_arr = array(); //hours array based on cron string - var $months_arr = array(); //months array based on cron string - - function getLastRan() - { - return explode(",", strftime("%M,%H,%d,%m,%w,%Y", $this->lastRan)); //Get the values for now in a format we can use - } - - function getLastRanUnix() - { - return $this->lastRan; - } - - function getDebug() - { - return $this->debug; - } - - function debug($str) - { - if (is_array($str)) - { - $this->debug .= "\nArray: "; - foreach($str as $k=>$v) - { - $this->debug .= "$k=>$v, "; - } - - } - else - { - $this->debug .= "\n$str"; - } - //echo nl2br($this->debug); - } - - /** - * Assumes that value is not *, and creates an array of valid numbers that - * the string represents. Returns an array. - */ - function expand_ranges($str) - { - if (strstr($str, ",")) - { - $arParts = explode(',', $str); - foreach ($arParts AS $part) - { - if (strstr($part, '-')) - { - $arRange = explode('-', $part); - for ($i = $arRange[0]; $i <= $arRange[1]; $i++) - { - $ret[] = $i; - } - } - else - { - $ret[] = $part; - } - } - } - elseif (strstr($str, '-')) - { - $arRange = explode('-', $str); - for ($i = $arRange[0]; $i <= $arRange[1]; $i++) - { - $ret[] = $i; - } - } - else - { - $ret[] = $str; - } - $ret = array_unique($ret); - sort($ret); - return $ret; - } - - function daysinmonth($month, $year) - { - return date('t', mktime(0, 0, 0, $month, 1, $year)); - } - - /** - * Calculate the last due time before this moment - */ - function calcLastRan($string) - { - - $tstart = microtime(); - $this->debug = ""; - $this->lastRan = 0; - $this->year = NULL; - $this->month = NULL; - $this->day = NULL; - $this->hour = NULL; - $this->minute = NULL; - $this->hours_arr = array(); - $this->minutes_arr = array(); - $this->months_arr = array(); - - $string = preg_replace('/[\s]{2,}/', ' ', $string); - - if (preg_match('/[^-,* \\d]/', $string) !== 0) - { - $this->debug("Cron String contains invalid character"); - return false; - } - - $this->debug("Working on cron schedule: $string"); - $this->bits = @explode(" ", $string); - - if (count($this->bits) != 5) - { - $this->debug("Cron string is invalid. Too many or too little sections after explode"); - return false; - } - - //put the current time into an array - $t = strftime("%M,%H,%d,%m,%w,%Y", time()); - $this->now = explode(",", $t); - - $this->year = $this->now[5]; - - $arMonths = $this->_getMonthsArray(); - - do - { - $this->month = array_pop($arMonths); - } - while ($this->month > $this->now[3]); - - if ($this->month === NULL) - { - $this->year = $this->year - 1; - $this->debug("Not due within this year. So checking the previous year " . $this->year); - $arMonths = $this->_getMonthsArray(); - $this->_prevMonth($arMonths); - } - elseif ($this->month == $this->now[3]) //now Sep, month = array(7,9,12) - { - $this->debug("Cron is due this month, getting days array."); - $arDays = $this->_getDaysArray($this->month, $this->year); - - do - { - $this->day = array_pop($arDays); - } - while ($this->day > $this->now[2]); - - if ($this->day === NULL) - { - $this->debug("Smallest day is even greater than today"); - $this->_prevMonth($arMonths); - } - elseif ($this->day == $this->now[2]) - { - $this->debug("Due to run today"); - $arHours = $this->_getHoursArray(); - - do - { - $this->hour = array_pop($arHours); - } - while ($this->hour > $this->now[1]); - - if ($this->hour === NULL) // now =2, arHours = array(3,5,7) - { - $this->debug("Not due this hour and some earlier hours, so go for previous day"); - $this->_prevDay($arDays, $arMonths); - } - elseif ($this->hour < $this->now[1]) //now =2, arHours = array(1,3,5) - { - $this->minute = $this->_getLastMinute(); - } - else // now =2, arHours = array(1,2,5) - { - $this->debug("Due this hour"); - $arMinutes = $this->_getMinutesArray(); - do - { - $this->minute = array_pop($arMinutes); - } - while ($this->minute > $this->now[0]); - - if ($this->minute === NULL) - { - $this->debug("Not due this minute, so go for previous hour."); - $this->_prevHour($arHours, $arDays, $arMonths); - } - else - { - $this->debug("Due this very minute or some earlier minutes before this moment within this hour."); - } - } - } - else - { - $this->debug("Cron was due on " . $this->day . " of this month"); - $this->hour = $this->_getLastHour(); - $this->minute = $this->_getLastMinute(); - } - } - else //now Sep, arrMonths=array(7, 10) - { - $this->debug("Cron was due before this month. Previous month is: " . $this->year . '-' . $this->month); - $this->day = $this->_getLastDay($this->month, $this->year); - if ($this->day === NULL) - { - //No scheduled date within this month. So we will try the previous month in the month array - $this->_prevMonth($arMonths); - } - else - { - $this->hour = $this->_getLastHour(); - $this->minute = $this->_getLastMinute(); - } - } - - $tend = microtime(); - $this->taken = $tend - $tstart; - $this->debug("Parsing $string taken " . $this->taken . " seconds"); - - //if the last due is beyond 1970 - if ($this->minute === NULL) - { - $this->debug("Error calculating last due time"); - return false; - } - else - { - $this->debug("LAST DUE: " . $this->hour . ":" . $this->minute . " on " . $this->day . "/" . $this->month . "/" . $this->year); - $this->lastRan = mktime($this->hour, $this->minute, 0, $this->month, $this->day, $this->year); - return true; - } - } - - //get the due time before current month - function _prevMonth($arMonths) - { - $this->month = array_pop($arMonths); - if ($this->month === NULL) - { - $this->year = $this->year -1; - if ($this->year <= 1970) - { - $this->debug("Can not calculate last due time. At least not before 1970.."); - } - else - { - $this->debug("Have to go for previous year " . $this->year); - $arMonths = $this->_getMonthsArray(); - $this->_prevMonth($arMonths); - } - } - else - { - $this->debug("Getting the last day for previous month: " . $this->year . '-' . $this->month); - $this->day = $this->_getLastDay($this->month, $this->year); - - if ($this->day === NULL) - { - //no available date schedule in this month - $this->_prevMonth($arMonths); - } - else - { - $this->hour = $this->_getLastHour(); - $this->minute = $this->_getLastMinute(); - } - } - - } - - //get the due time before current day - function _prevDay($arDays, $arMonths) - { - $this->debug("Go for the previous day"); - $this->day = array_pop($arDays); - if ($this->day === NULL) - { - $this->debug("Have to go for previous month"); - $this->_prevMonth($arMonths); - } - else - { - $this->hour = $this->_getLastHour(); - $this->minute = $this->_getLastMinute(); - } - } - - //get the due time before current hour - function _prevHour($arHours, $arDays, $arMonths) - { - $this->debug("Going for previous hour"); - $this->hour = array_pop($arHours); - if ($this->hour === NULL) - { - $this->debug("Have to go for previous day"); - $this->_prevDay($arDays, $arMonths); - } - else - { - $this->minute = $this->_getLastMinute(); - } - } - - //not used at the moment - function _getLastMonth() - { - $months = $this->_getMonthsArray(); - $month = array_pop($months); - - return $month; - } - - function _getLastDay($month, $year) - { - //put the available days for that month into an array - $days = $this->_getDaysArray($month, $year); - $day = array_pop($days); - - return $day; - } - - function _getLastHour() - { - $hours = $this->_getHoursArray(); - $hour = array_pop($hours); - - return $hour; - } - - function _getLastMinute() - { - $minutes = $this->_getMinutesArray(); - $minute = array_pop($minutes); - - return $minute; - } - - //remove the out of range array elements. $arr should be sorted already and does not contain duplicates - function _sanitize ($arr, $low, $high) - { - $count = count($arr); - for ($i = 0; $i <= ($count - 1); $i++) - { - if ($arr[$i] < $low) - { - $this->debug("Remove out of range element. {$arr[$i]} is outside $low - $high"); - unset($arr[$i]); - } - else - { - break; - } - } - - for ($i = ($count - 1); $i >= 0; $i--) - { - if ($arr[$i] > $high) - { - $this->debug("Remove out of range element. {$arr[$i]} is outside $low - $high"); - unset ($arr[$i]); - } - else - { - break; - } - } - - //re-assign keys - sort($arr); - return $arr; - } - - //given a month/year, list all the days within that month fell into the week days list. - function _getDaysArray($month, $year = 0) - { - if ($year == 0) - { - $year = $this->year; - } - - $days = array(); - - //return everyday of the month if both bit[2] and bit[4] are '*' - if ($this->bits[2] == '*' AND $this->bits[4] == '*') - { - $days = $this->getDays($month, $year); - } - else - { - //create an array for the weekdays - if ($this->bits[4] == '*') - { - for ($i = 0; $i <= 6; $i++) - { - $arWeekdays[] = $i; - } - } - else - { - $arWeekdays = $this->expand_ranges($this->bits[4]); - $arWeekdays = $this->_sanitize($arWeekdays, 0, 7); - - //map 7 to 0, both represents Sunday. Array is sorted already! - if (in_array(7, $arWeekdays)) - { - if (in_array(0, $arWeekdays)) - { - array_pop($arWeekdays); - } - else - { - $tmp[] = 0; - array_pop($arWeekdays); - $arWeekdays = array_merge($tmp, $arWeekdays); - } - } - } - $this->debug("Array for the weekdays"); - $this->debug($arWeekdays); - - if ($this->bits[2] == '*') - { - $daysmonth = $this->getDays($month, $year); - } - else - { - $daysmonth = $this->expand_ranges($this->bits[2]); - // so that we do not end up with 31 of Feb - $daysinmonth = $this->daysinmonth($month, $year); - $daysmonth = $this->_sanitize($daysmonth, 1, $daysinmonth); - } - - //Now match these days with weekdays - foreach ($daysmonth AS $day) - { - $wkday = date('w', mktime(0, 0, 0, $month, $day, $year)); - if (in_array($wkday, $arWeekdays)) - { - $days[] = $day; - } - } - } - $this->debug("Days array matching weekdays for $year-$month"); - $this->debug($days); - return $days; - } - - //given a month/year, return an array containing all the days in that month - function getDays($month, $year) - { - $daysinmonth = $this->daysinmonth($month, $year); - $this->debug("Number of days in $year-$month : $daysinmonth"); - $days = array(); - for ($i = 1; $i <= $daysinmonth; $i++) - { - $days[] = $i; - } - return $days; - } - - function _getHoursArray() - { - if (empty($this->hours_arr)) - { - $hours = array(); - - if ($this->bits[1] == '*') - { - for ($i = 0; $i <= 23; $i++) - { - $hours[] = $i; - } - } - else - { - $hours = $this->expand_ranges($this->bits[1]); - $hours = $this->_sanitize($hours, 0, 23); - } - - $this->debug("Hour array"); - $this->debug($hours); - $this->hours_arr = $hours; - } - return $this->hours_arr; - } - - function _getMinutesArray() - { - if (empty($this->minutes_arr)) - { - $minutes = array(); - - if ($this->bits[0] == '*') - { - for ($i = 0; $i <= 60; $i++) - { - $minutes[] = $i; - } - } - else - { - $minutes = $this->expand_ranges($this->bits[0]); - $minutes = $this->_sanitize($minutes, 0, 59); - } - $this->debug("Minutes array"); - $this->debug($minutes); - $this->minutes_arr = $minutes; - } - return $this->minutes_arr; - } - - function _getMonthsArray() - { - if (empty($this->months_arr)) - { - $months = array(); - if ($this->bits[3] == '*') - { - for ($i = 1; $i <= 12; $i++) - { - $months[] = $i; - } - } - else - { - $months = $this->expand_ranges($this->bits[3]); - $months = $this->_sanitize($months, 1, 12); - } - $this->debug("Months array"); - $this->debug($months); - $this->months_arr = $months; - } - return $this->months_arr; - } + var $bits = Array(); //exploded String like 0 1 * * * + var $now = Array(); //Array of cron-style entries for time() + var $lastRan; //Timestamp of last ran time. + var $taken; + var $debug; + var $year; + var $month; + var $day; + var $hour; + var $minute; + var $minutes_arr = array(); //minutes array based on cron string + var $hours_arr = array(); //hours array based on cron string + var $months_arr = array(); //months array based on cron string + + function getLastRan() + { + return explode(",", strftime("%M,%H,%d,%m,%w,%Y", $this->lastRan)); //Get the values for now in a format we can use + } + + function getLastRanUnix() + { + return $this->lastRan; + } + + function getDebug() + { + return $this->debug; + } + + function debug($str) + { + if (is_array($str)) + { + $this->debug .= "\nArray: "; + foreach($str as $k=>$v) + { + $this->debug .= "$k=>$v, "; + } + + } + else + { + $this->debug .= "\n$str"; + } + //echo nl2br($this->debug); + } + + /** + * Assumes that value is not *, and creates an array of valid numbers that + * the string represents. Returns an array. + */ + function expand_ranges($str) + { + if (strstr($str, ",")) + { + $arParts = explode(',', $str); + foreach ($arParts AS $part) + { + if (strstr($part, '-')) + { + $arRange = explode('-', $part); + for ($i = $arRange[0]; $i <= $arRange[1]; $i++) + { + $ret[] = $i; + } + } + else + { + $ret[] = $part; + } + } + } + elseif (strstr($str, '-')) + { + $arRange = explode('-', $str); + for ($i = $arRange[0]; $i <= $arRange[1]; $i++) + { + $ret[] = $i; + } + } + else + { + $ret[] = $str; + } + $ret = array_unique($ret); + sort($ret); + return $ret; + } + + function daysinmonth($month, $year) + { + return date('t', mktime(0, 0, 0, $month, 1, $year)); + } + + /** + * Calculate the last due time before this moment + */ + function calcLastRan($string) + { + + $tstart = microtime(); + $this->debug = ""; + $this->lastRan = 0; + $this->year = NULL; + $this->month = NULL; + $this->day = NULL; + $this->hour = NULL; + $this->minute = NULL; + $this->hours_arr = array(); + $this->minutes_arr = array(); + $this->months_arr = array(); + + $string = preg_replace('/[\s]{2,}/', ' ', $string); + + if (preg_match('/[^-,* \\d]/', $string) !== 0) + { + $this->debug("Cron String contains invalid character"); + return false; + } + + $this->debug("Working on cron schedule: $string"); + $this->bits = @explode(" ", $string); + + if (count($this->bits) != 5) + { + $this->debug("Cron string is invalid. Too many or too little sections after explode"); + return false; + } + + //put the current time into an array + $t = strftime("%M,%H,%d,%m,%w,%Y", time()); + $this->now = explode(",", $t); + + $this->year = $this->now[5]; + + $arMonths = $this->_getMonthsArray(); + + do + { + $this->month = array_pop($arMonths); + } + while ($this->month > $this->now[3]); + + if ($this->month === NULL) + { + $this->year = $this->year - 1; + $this->debug("Not due within this year. So checking the previous year " . $this->year); + $arMonths = $this->_getMonthsArray(); + $this->_prevMonth($arMonths); + } + elseif ($this->month == $this->now[3]) //now Sep, month = array(7,9,12) + { + $this->debug("Cron is due this month, getting days array."); + $arDays = $this->_getDaysArray($this->month, $this->year); + + do + { + $this->day = array_pop($arDays); + } + while ($this->day > $this->now[2]); + + if ($this->day === NULL) + { + $this->debug("Smallest day is even greater than today"); + $this->_prevMonth($arMonths); + } + elseif ($this->day == $this->now[2]) + { + $this->debug("Due to run today"); + $arHours = $this->_getHoursArray(); + + do + { + $this->hour = array_pop($arHours); + } + while ($this->hour > $this->now[1]); + + if ($this->hour === NULL) // now =2, arHours = array(3,5,7) + { + $this->debug("Not due this hour and some earlier hours, so go for previous day"); + $this->_prevDay($arDays, $arMonths); + } + elseif ($this->hour < $this->now[1]) //now =2, arHours = array(1,3,5) + { + $this->minute = $this->_getLastMinute(); + } + else // now =2, arHours = array(1,2,5) + { + $this->debug("Due this hour"); + $arMinutes = $this->_getMinutesArray(); + do + { + $this->minute = array_pop($arMinutes); + } + while ($this->minute > $this->now[0]); + + if ($this->minute === NULL) + { + $this->debug("Not due this minute, so go for previous hour."); + $this->_prevHour($arHours, $arDays, $arMonths); + } + else + { + $this->debug("Due this very minute or some earlier minutes before this moment within this hour."); + } + } + } + else + { + $this->debug("Cron was due on " . $this->day . " of this month"); + $this->hour = $this->_getLastHour(); + $this->minute = $this->_getLastMinute(); + } + } + else //now Sep, arrMonths=array(7, 10) + { + $this->debug("Cron was due before this month. Previous month is: " . $this->year . '-' . $this->month); + $this->day = $this->_getLastDay($this->month, $this->year); + if ($this->day === NULL) + { + //No scheduled date within this month. So we will try the previous month in the month array + $this->_prevMonth($arMonths); + } + else + { + $this->hour = $this->_getLastHour(); + $this->minute = $this->_getLastMinute(); + } + } + + $tend = microtime(); + $this->taken = $tend - $tstart; + $this->debug("Parsing $string taken " . $this->taken . " seconds"); + + //if the last due is beyond 1970 + if ($this->minute === NULL) + { + $this->debug("Error calculating last due time"); + return false; + } + else + { + $this->debug("LAST DUE: " . $this->hour . ":" . $this->minute . " on " . $this->day . "/" . $this->month . "/" . $this->year); + $this->lastRan = mktime($this->hour, $this->minute, 0, $this->month, $this->day, $this->year); + return true; + } + } + + //get the due time before current month + function _prevMonth($arMonths) + { + $this->month = array_pop($arMonths); + if ($this->month === NULL) + { + $this->year = $this->year -1; + if ($this->year <= 1970) + { + $this->debug("Can not calculate last due time. At least not before 1970.."); + } + else + { + $this->debug("Have to go for previous year " . $this->year); + $arMonths = $this->_getMonthsArray(); + $this->_prevMonth($arMonths); + } + } + else + { + $this->debug("Getting the last day for previous month: " . $this->year . '-' . $this->month); + $this->day = $this->_getLastDay($this->month, $this->year); + + if ($this->day === NULL) + { + //no available date schedule in this month + $this->_prevMonth($arMonths); + } + else + { + $this->hour = $this->_getLastHour(); + $this->minute = $this->_getLastMinute(); + } + } + + } + + //get the due time before current day + function _prevDay($arDays, $arMonths) + { + $this->debug("Go for the previous day"); + $this->day = array_pop($arDays); + if ($this->day === NULL) + { + $this->debug("Have to go for previous month"); + $this->_prevMonth($arMonths); + } + else + { + $this->hour = $this->_getLastHour(); + $this->minute = $this->_getLastMinute(); + } + } + + //get the due time before current hour + function _prevHour($arHours, $arDays, $arMonths) + { + $this->debug("Going for previous hour"); + $this->hour = array_pop($arHours); + if ($this->hour === NULL) + { + $this->debug("Have to go for previous day"); + $this->_prevDay($arDays, $arMonths); + } + else + { + $this->minute = $this->_getLastMinute(); + } + } + + //not used at the moment + function _getLastMonth() + { + $months = $this->_getMonthsArray(); + $month = array_pop($months); + + return $month; + } + + function _getLastDay($month, $year) + { + //put the available days for that month into an array + $days = $this->_getDaysArray($month, $year); + $day = array_pop($days); + + return $day; + } + + function _getLastHour() + { + $hours = $this->_getHoursArray(); + $hour = array_pop($hours); + + return $hour; + } + + function _getLastMinute() + { + $minutes = $this->_getMinutesArray(); + $minute = array_pop($minutes); + + return $minute; + } + + //remove the out of range array elements. $arr should be sorted already and does not contain duplicates + function _sanitize ($arr, $low, $high) + { + $count = count($arr); + for ($i = 0; $i <= ($count - 1); $i++) + { + if ($arr[$i] < $low) + { + $this->debug("Remove out of range element. {$arr[$i]} is outside $low - $high"); + unset($arr[$i]); + } + else + { + break; + } + } + + for ($i = ($count - 1); $i >= 0; $i--) + { + if ($arr[$i] > $high) + { + $this->debug("Remove out of range element. {$arr[$i]} is outside $low - $high"); + unset ($arr[$i]); + } + else + { + break; + } + } + + //re-assign keys + sort($arr); + return $arr; + } + + //given a month/year, list all the days within that month fell into the week days list. + function _getDaysArray($month, $year = 0) + { + if ($year == 0) + { + $year = $this->year; + } + + $days = array(); + + //return everyday of the month if both bit[2] and bit[4] are '*' + if ($this->bits[2] == '*' AND $this->bits[4] == '*') + { + $days = $this->getDays($month, $year); + } + else + { + //create an array for the weekdays + if ($this->bits[4] == '*') + { + for ($i = 0; $i <= 6; $i++) + { + $arWeekdays[] = $i; + } + } + else + { + $arWeekdays = $this->expand_ranges($this->bits[4]); + $arWeekdays = $this->_sanitize($arWeekdays, 0, 7); + + //map 7 to 0, both represents Sunday. Array is sorted already! + if (in_array(7, $arWeekdays)) + { + if (in_array(0, $arWeekdays)) + { + array_pop($arWeekdays); + } + else + { + $tmp[] = 0; + array_pop($arWeekdays); + $arWeekdays = array_merge($tmp, $arWeekdays); + } + } + } + $this->debug("Array for the weekdays"); + $this->debug($arWeekdays); + + if ($this->bits[2] == '*') + { + $daysmonth = $this->getDays($month, $year); + } + else + { + $daysmonth = $this->expand_ranges($this->bits[2]); + // so that we do not end up with 31 of Feb + $daysinmonth = $this->daysinmonth($month, $year); + $daysmonth = $this->_sanitize($daysmonth, 1, $daysinmonth); + } + + //Now match these days with weekdays + foreach ($daysmonth AS $day) + { + $wkday = date('w', mktime(0, 0, 0, $month, $day, $year)); + if (in_array($wkday, $arWeekdays)) + { + $days[] = $day; + } + } + } + $this->debug("Days array matching weekdays for $year-$month"); + $this->debug($days); + return $days; + } + + //given a month/year, return an array containing all the days in that month + function getDays($month, $year) + { + $daysinmonth = $this->daysinmonth($month, $year); + $this->debug("Number of days in $year-$month : $daysinmonth"); + $days = array(); + for ($i = 1; $i <= $daysinmonth; $i++) + { + $days[] = $i; + } + return $days; + } + + function _getHoursArray() + { + if (empty($this->hours_arr)) + { + $hours = array(); + + if ($this->bits[1] == '*') + { + for ($i = 0; $i <= 23; $i++) + { + $hours[] = $i; + } + } + else + { + $hours = $this->expand_ranges($this->bits[1]); + $hours = $this->_sanitize($hours, 0, 23); + } + + $this->debug("Hour array"); + $this->debug($hours); + $this->hours_arr = $hours; + } + return $this->hours_arr; + } + + function _getMinutesArray() + { + if (empty($this->minutes_arr)) + { + $minutes = array(); + + if ($this->bits[0] == '*') + { + for ($i = 0; $i <= 60; $i++) + { + $minutes[] = $i; + } + } + else + { + $minutes = $this->expand_ranges($this->bits[0]); + $minutes = $this->_sanitize($minutes, 0, 59); + } + $this->debug("Minutes array"); + $this->debug($minutes); + $this->minutes_arr = $minutes; + } + return $this->minutes_arr; + } + + function _getMonthsArray() + { + if (empty($this->months_arr)) + { + $months = array(); + if ($this->bits[3] == '*') + { + for ($i = 1; $i <= 12; $i++) + { + $months[] = $i; + } + } + else + { + $months = $this->expand_ranges($this->bits[3]); + $months = $this->_sanitize($months, 1, 12); + } + $this->debug("Months array"); + $this->debug($months); + $this->months_arr = $months; + } + return $this->months_arr; + } } ?> \ No newline at end of file diff --git a/includes/Daemon.class.php b/includes/Daemon.class.php index 70755d6c6..ddaa3c150 100644 --- a/includes/Daemon.class.php +++ b/includes/Daemon.class.php @@ -1,380 +1,380 @@ -= 4.3.0 or PHP 5 - * PHP compiled with: - * --enable-sigchild - * --enable-pcntl - * - * @package binarychoice.system.unix - * @author Michal 'Seth' Golebiowski - * @copyright Copyright 2005 Seth - * @since 1.0.3 - */ -class Daemon -{ - /**#@+ - * @access public - */ - /** - * User ID - * - * @var int - * @since 1.0 - */ - var $userID = 99; - - /** - * Group ID - * - * @var integer - * @since 1.0 - */ - var $groupID = 99; - - /** - * Terminate daemon when set identity failure ? - * - * @var bool - * @since 1.0.3 - */ - var $requireSetIdentity = false; - - /** - * Path to PID file - * - * @var string - * @since 1.0.1 - */ - var $pidFileLocation = '/tmp/daemon.pid'; - - /** - * Home path - * - * @var string - * @since 1.0 - */ - var $homePath = '/'; - /**#@-*/ - - - /**#@+ - * @access protected - */ - /** - * Current process ID - * - * @var int - * @since 1.0 - */ - var $_pid = 0; - - /** - * Is this process a children - * - * @var boolean - * @since 1.0 - */ - var $_isChildren = false; - - /** - * Is daemon running - * - * @var boolean - * @since 1.0 - */ - var $_isRunning = false; - /**#@-*/ - - - /** - * Constructor - * - * @access public - * @since 1.0 - * @return void - */ - function __construct() - { - error_reporting(0); - set_time_limit(0); - ob_implicit_flush(); - - } - - /** - * Starts daemon - * - * @access public - * @since 1.0 - * @return bool - */ - function start() - { - $this->_logMessage('Starting daemon'); - - if (!$this->_daemonize()) - { - $this->_logMessage('Could not start daemon', DLOG_ERROR); - - return false; - } - - - $this->_logMessage('Running...'); - - $this->_isRunning = true; - - - while ($this->_isRunning) - { - $this->_doTask(); - } - - return true; - } - - /** - * Stops daemon - * - * @access public - * @since 1.0 - * @return void - */ - function stop() - { - $this->_logMessage('Stoping daemon'); - - $this->_isRunning = false; - } - - /** - * Do task - * - * @access protected - * @since 1.0 - * @return void - */ - function _doTask() - { - // override this method - } - - /** - * Logs message - * - * @access protected - * @since 1.0 - * @return void - */ - function _logMessage($msg, $level = DLOG_NOTICE) - { - // override this method - } - - /** - * Daemonize - * - * Several rules or characteristics that most daemons possess: - * 1) Check is daemon already running - * 2) Fork child process - * 3) Sets identity - * 4) Make current process a session laeder - * 5) Write process ID to file - * 6) Change home path - * 7) umask(0) - * - * @access private - * @since 1.0 - * @return void - */ - function _daemonize() - { - ob_end_flush(); - - if ($this->_isDaemonRunning()) - { - // Deamon is already running. Exiting - return false; - } - - if (!$this->_fork()) - { - // Coudn't fork. Exiting. - return false; - } - - if (!$this->_setIdentity() && $this->requireSetIdentity) - { - // Required identity set failed. Exiting - return false; - } - - if (!posix_setsid()) - { - $this->_logMessage('Could not make the current process a session leader', DLOG_ERROR); - - return false; - } - - if (!$fp = @fopen($this->pidFileLocation, 'w')) - { - $this->_logMessage('Could not write to PID file', DLOG_ERROR); - - return false; - } - else - { - fputs($fp, $this->_pid); - fclose($fp); - } - - @chdir($this->homePath); - umask(0); - - declare(ticks = 1); - - pcntl_signal(SIGCHLD, array(&$this, 'sigHandler')); - pcntl_signal(SIGTERM, array(&$this, 'sigHandler')); - - return true; - } - - /** - * Cheks is daemon already running - * - * @access private - * @since 1.0.3 - * @return bool - */ - function _isDaemonRunning() - { - $oldPid = @file_get_contents($this->pidFileLocation); - - if ($oldPid !== false && posix_kill(trim($oldPid),0)) - { - $this->_logMessage('Daemon already running with PID: '.$oldPid, (DLOG_TO_CONSOLE | DLOG_ERROR)); - - return true; - } - else - { - return false; - } - } - - /** - * Forks process - * - * @access private - * @since 1.0 - * @return bool - */ - function _fork() - { - $this->_logMessage('Forking...'); - - if (!function_exists('pcntl_fork')) { - $this->_logMessage('Forking 2...'); - } - $pid = pcntl_fork(); - - if ($pid == -1) // error - { - $this->_logMessage('Could not fork', DLOG_ERROR); - - return false; - } - else if ($pid) // parent - { - $this->_logMessage('Killing parent'); - - exit(); - } - else // children - { - $this->_isChildren = true; - $this->_pid = posix_getpid(); - - return true; - } - } - - /** - * Sets identity of a daemon and returns result - * - * @access private - * @since 1.0 - * @return bool - */ - function _setIdentity() - { - if (!posix_setgid($this->groupID) || !posix_setuid($this->userID)) - { - $this->_logMessage('Could not set identity', DLOG_WARNING); - - return false; - } - else - { - return true; - } - } - - /** - * Signals handler - * - * @access public - * @since 1.0 - * @return void - */ - function sigHandler($sigNo) - { - switch ($sigNo) - { - case SIGTERM: // Shutdown - $this->_logMessage('Shutdown signal'); - exit(); - break; - - case SIGCHLD: // Halt - $this->_logMessage('Halt signal'); - while (pcntl_waitpid(-1, $status, WNOHANG) > 0); - break; - } - } - - /** - * Releases daemon pid file - * This method is called on exit (destructor like) - * - * @access public - * @since 1.0 - * @return void - */ - function __destruct() - { - if ($this->_isChildren && file_exists($this->pidFileLocation)) - { - $this->_logMessage('Releasing daemon'); - - unlink($this->pidFileLocation); - } - } -} += 4.3.0 or PHP 5 + * PHP compiled with: + * --enable-sigchild + * --enable-pcntl + * + * @package binarychoice.system.unix + * @author Michal 'Seth' Golebiowski + * @copyright Copyright 2005 Seth + * @since 1.0.3 + */ +class Daemon +{ + /**#@+ + * @access public + */ + /** + * User ID + * + * @var int + * @since 1.0 + */ + var $userID = 99; + + /** + * Group ID + * + * @var integer + * @since 1.0 + */ + var $groupID = 99; + + /** + * Terminate daemon when set identity failure ? + * + * @var bool + * @since 1.0.3 + */ + var $requireSetIdentity = false; + + /** + * Path to PID file + * + * @var string + * @since 1.0.1 + */ + var $pidFileLocation = '/tmp/daemon.pid'; + + /** + * Home path + * + * @var string + * @since 1.0 + */ + var $homePath = '/'; + /**#@-*/ + + + /**#@+ + * @access protected + */ + /** + * Current process ID + * + * @var int + * @since 1.0 + */ + var $_pid = 0; + + /** + * Is this process a children + * + * @var boolean + * @since 1.0 + */ + var $_isChildren = false; + + /** + * Is daemon running + * + * @var boolean + * @since 1.0 + */ + var $_isRunning = false; + /**#@-*/ + + + /** + * Constructor + * + * @access public + * @since 1.0 + * @return void + */ + function __construct() + { + error_reporting(0); + set_time_limit(0); + ob_implicit_flush(); + + } + + /** + * Starts daemon + * + * @access public + * @since 1.0 + * @return bool + */ + function start() + { + $this->_logMessage('Starting daemon'); + + if (!$this->_daemonize()) + { + $this->_logMessage('Could not start daemon', DLOG_ERROR); + + return false; + } + + + $this->_logMessage('Running...'); + + $this->_isRunning = true; + + + while ($this->_isRunning) + { + $this->_doTask(); + } + + return true; + } + + /** + * Stops daemon + * + * @access public + * @since 1.0 + * @return void + */ + function stop() + { + $this->_logMessage('Stoping daemon'); + + $this->_isRunning = false; + } + + /** + * Do task + * + * @access protected + * @since 1.0 + * @return void + */ + function _doTask() + { + // override this method + } + + /** + * Logs message + * + * @access protected + * @since 1.0 + * @return void + */ + function _logMessage($msg, $level = DLOG_NOTICE) + { + // override this method + } + + /** + * Daemonize + * + * Several rules or characteristics that most daemons possess: + * 1) Check is daemon already running + * 2) Fork child process + * 3) Sets identity + * 4) Make current process a session laeder + * 5) Write process ID to file + * 6) Change home path + * 7) umask(0) + * + * @access private + * @since 1.0 + * @return void + */ + function _daemonize() + { + ob_end_flush(); + + if ($this->_isDaemonRunning()) + { + // Deamon is already running. Exiting + return false; + } + + if (!$this->_fork()) + { + // Coudn't fork. Exiting. + return false; + } + + if (!$this->_setIdentity() && $this->requireSetIdentity) + { + // Required identity set failed. Exiting + return false; + } + + if (!posix_setsid()) + { + $this->_logMessage('Could not make the current process a session leader', DLOG_ERROR); + + return false; + } + + if (!$fp = @fopen($this->pidFileLocation, 'w')) + { + $this->_logMessage('Could not write to PID file', DLOG_ERROR); + + return false; + } + else + { + fputs($fp, $this->_pid); + fclose($fp); + } + + @chdir($this->homePath); + umask(0); + + declare(ticks = 1); + + pcntl_signal(SIGCHLD, array(&$this, 'sigHandler')); + pcntl_signal(SIGTERM, array(&$this, 'sigHandler')); + + return true; + } + + /** + * Cheks is daemon already running + * + * @access private + * @since 1.0.3 + * @return bool + */ + function _isDaemonRunning() + { + $oldPid = @file_get_contents($this->pidFileLocation); + + if ($oldPid !== false && posix_kill(trim($oldPid),0)) + { + $this->_logMessage('Daemon already running with PID: '.$oldPid, (DLOG_TO_CONSOLE | DLOG_ERROR)); + + return true; + } + else + { + return false; + } + } + + /** + * Forks process + * + * @access private + * @since 1.0 + * @return bool + */ + function _fork() + { + $this->_logMessage('Forking...'); + + if (!function_exists('pcntl_fork')) { + $this->_logMessage('Forking 2...'); + } + $pid = pcntl_fork(); + + if ($pid == -1) // error + { + $this->_logMessage('Could not fork', DLOG_ERROR); + + return false; + } + else if ($pid) // parent + { + $this->_logMessage('Killing parent'); + + exit(); + } + else // children + { + $this->_isChildren = true; + $this->_pid = posix_getpid(); + + return true; + } + } + + /** + * Sets identity of a daemon and returns result + * + * @access private + * @since 1.0 + * @return bool + */ + function _setIdentity() + { + if (!posix_setgid($this->groupID) || !posix_setuid($this->userID)) + { + $this->_logMessage('Could not set identity', DLOG_WARNING); + + return false; + } + else + { + return true; + } + } + + /** + * Signals handler + * + * @access public + * @since 1.0 + * @return void + */ + function sigHandler($sigNo) + { + switch ($sigNo) + { + case SIGTERM: // Shutdown + $this->_logMessage('Shutdown signal'); + exit(); + break; + + case SIGCHLD: // Halt + $this->_logMessage('Halt signal'); + while (pcntl_waitpid(-1, $status, WNOHANG) > 0); + break; + } + } + + /** + * Releases daemon pid file + * This method is called on exit (destructor like) + * + * @access public + * @since 1.0 + * @return void + */ + function __destruct() + { + if ($this->_isChildren && file_exists($this->pidFileLocation)) + { + $this->_logMessage('Releasing daemon'); + + unlink($this->pidFileLocation); + } + } +} ?> \ No newline at end of file diff --git a/includes/Snoopy.class.php b/includes/Snoopy.class.php index dea44caeb..e4c1ba8bd 100644 --- a/includes/Snoopy.class.php +++ b/includes/Snoopy.class.php @@ -109,12 +109,12 @@ class Snoopy var $_fp_timeout = 30; // timeout for socket connection /*======================================================================*\ - Function: fetch - Purpose: fetch the contents of a web page + Function: fetch + Purpose: fetch the contents of a web page (and possibly other protocols in the future like ftp, nntp, gopher, etc.) - Input: $URI the location of the page to fetch - Output: $this->results the output text from the fetch + Input: $URI the location of the page to fetch + Output: $this->results the output text from the fetch \*======================================================================*/ function fetch($URI) @@ -196,14 +196,14 @@ function fetch($URI) } /*======================================================================*\ - Function: submit - Purpose: submit an http(s) form - Input: $URI the location to post the data - $formvars the formvars to use. + Function: submit + Purpose: submit an http(s) form + Input: $URI the location to post the data + $formvars the formvars to use. format: $formvars["var"] = "val"; $formfiles an array of files to submit format: $formfiles["var"] = "/dir/filename.ext"; - Output: $this->results the text output from the post + Output: $this->results the text output from the post \*======================================================================*/ function submit($URI, $formvars = "", $formfiles = "") @@ -293,10 +293,10 @@ function submit($URI, $formvars = "", $formfiles = "") } /*======================================================================*\ - Function: fetchlinks - Purpose: fetch the links from a web page - Input: $URI where you are fetching from - Output: $this->results an array of the URLs + Function: fetchlinks + Purpose: fetch the links from a web page + Input: $URI where you are fetching from + Output: $this->results an array of the URLs \*======================================================================*/ function fetchlinks($URI) @@ -318,10 +318,10 @@ function fetchlinks($URI) } /*======================================================================*\ - Function: fetchform - Purpose: fetch the form elements from a web page - Input: $URI where you are fetching from - Output: $this->results the resulting html form + Function: fetchform + Purpose: fetch the form elements from a web page + Input: $URI where you are fetching from + Output: $this->results the resulting html form \*======================================================================*/ function fetchform($URI) @@ -342,10 +342,10 @@ function fetchform($URI) /*======================================================================*\ - Function: fetchtext - Purpose: fetch the text from a web page, stripping the links - Input: $URI where you are fetching from - Output: $this->results the text from the web page + Function: fetchtext + Purpose: fetch the text from a web page, stripping the links + Input: $URI where you are fetching from + Output: $this->results the text from the web page \*======================================================================*/ function fetchtext($URI) @@ -362,10 +362,10 @@ function fetchtext($URI) } /*======================================================================*\ - Function: submitlinks - Purpose: grab links from a form submission - Input: $URI where you are submitting from - Output: $this->results an array of the links from the post + Function: submitlinks + Purpose: grab links from a form submission + Input: $URI where you are submitting from + Output: $this->results an array of the links from the post \*======================================================================*/ function submitlinks($URI, $formvars = "", $formfiles = "") @@ -390,10 +390,10 @@ function submitlinks($URI, $formvars = "", $formfiles = "") } /*======================================================================*\ - Function: submittext - Purpose: grab text from a form submission - Input: $URI where you are submitting from - Output: $this->results the text from the web page + Function: submittext + Purpose: grab text from a form submission + Input: $URI where you are submitting from + Output: $this->results the text from the web page \*======================================================================*/ function submittext($URI, $formvars = "", $formfiles = "") @@ -419,8 +419,8 @@ function submittext($URI, $formvars = "", $formfiles = "") /*======================================================================*\ - Function: set_submit_multipart - Purpose: Set the form submission content type to + Function: set_submit_multipart + Purpose: Set the form submission content type to multipart/form-data \*======================================================================*/ function set_submit_multipart() @@ -431,8 +431,8 @@ function set_submit_multipart() /*======================================================================*\ - Function: set_submit_normal - Purpose: Set the form submission content type to + Function: set_submit_normal + Purpose: Set the form submission content type to application/x-www-form-urlencoded \*======================================================================*/ function set_submit_normal() @@ -450,19 +450,19 @@ function set_submit_normal() /*======================================================================*\ - Function: _striplinks - Purpose: strip the hyperlinks from an html document - Input: $document document to strip. - Output: $match an array of the links + Function: _striplinks + Purpose: strip the hyperlinks from an html document + Input: $document document to strip. + Output: $match an array of the links \*======================================================================*/ function _striplinks($document) { - preg_match_all("'<\s*a\s.*?href\s*=\s* # find ]+)) # if quote found, match up to next matching - # quote, otherwise match up to next space - 'isx", $document, $links); + preg_match_all("'<\s*a\s.*?href\s*=\s* # find ]+)) # if quote found, match up to next matching + # quote, otherwise match up to next space + 'isx", $document, $links); // catenate the non-empty matches from the conditional subpattern @@ -482,10 +482,10 @@ function _striplinks($document) } /*======================================================================*\ - Function: _stripform - Purpose: strip the form elements from an html document - Input: $document document to strip. - Output: $match an array of the links + Function: _stripform + Purpose: strip the form elements from an html document + Input: $document document to strip. + Output: $match an array of the links \*======================================================================*/ function _stripform($document) @@ -501,10 +501,10 @@ function _stripform($document) /*======================================================================*\ - Function: _striptext - Purpose: strip the text from an html document - Input: $document document to strip. - Output: $text the resulting text + Function: _striptext + Purpose: strip the text from an html document + Input: $document document to strip. + Output: $text the resulting text \*======================================================================*/ function _striptext($document) @@ -569,11 +569,11 @@ function _striptext($document) } /*======================================================================*\ - Function: _expandlinks - Purpose: expand each link into a fully qualified URL - Input: $links the links to qualify - $URI the full URI to get the base from - Output: $expandedLinks the expanded links + Function: _expandlinks + Purpose: expand each link into a fully qualified URL + Input: $links the links to qualify + $URI the full URI to get the base from + Output: $expandedLinks the expanded links \*======================================================================*/ function _expandlinks($links, $URI) @@ -607,12 +607,12 @@ function _expandlinks($links, $URI) } /*======================================================================*\ - Function: _httprequest - Purpose: go get the http(s) data from the server - Input: $url the url to fetch - $fp the current open file pointer - $URI the full URI - $body body contents to send if any (POST) + Function: _httprequest + Purpose: go get the http(s) data from the server + Input: $url the url to fetch + $fp the current open file pointer + $URI the full URI + $body body contents to send if any (POST) Output: \*======================================================================*/ @@ -790,8 +790,8 @@ function _httprequest($url, $fp, $URI, $http_method, $content_type = "", $body = } /*======================================================================*\ - Function: setcookies() - Purpose: set cookies for a redirection + Function: setcookies() + Purpose: set cookies for a redirection \*======================================================================*/ function setcookies() @@ -805,9 +805,9 @@ function setcookies() /*======================================================================*\ - Function: _check_timeout - Purpose: checks whether timeout has occurred - Input: $fp file pointer + Function: _check_timeout + Purpose: checks whether timeout has occurred + Input: $fp file pointer \*======================================================================*/ function _check_timeout($fp) @@ -823,9 +823,9 @@ function _check_timeout($fp) } /*======================================================================*\ - Function: _connect - Purpose: make a socket connection - Input: $fp file pointer + Function: _connect + Purpose: make a socket connection + Input: $fp file pointer \*======================================================================*/ function _connect(&$fp) @@ -911,9 +911,9 @@ function _connect(&$fp) } /*======================================================================*\ - Function: _disconnect - Purpose: disconnect a socket connection - Input: $fp file pointer + Function: _disconnect + Purpose: disconnect a socket connection + Input: $fp file pointer \*======================================================================*/ function _disconnect($fp) @@ -923,11 +923,11 @@ function _disconnect($fp) /*======================================================================*\ - Function: _prepare_post_body - Purpose: Prepare post body according to encoding type - Input: $formvars - form variables + Function: _prepare_post_body + Purpose: Prepare post body according to encoding type + Input: $formvars - form variables $formfiles - form upload files - Output: post body + Output: post body \*======================================================================*/ function _prepare_post_body($formvars, $formfiles) @@ -993,9 +993,9 @@ function _prepare_post_body($formvars, $formfiles) } /*======================================================================*\ - Function: getResults - Purpose: return the results of a request - Output: string results + Function: getResults + Purpose: return the results of a request + Output: string results \*======================================================================*/ function getResults() diff --git a/includes/httpclient-2016-05-02/http.php b/includes/httpclient-2016-05-02/http.php index a84ceabfd..4d4b882f9 100644 --- a/includes/httpclient-2016-05-02/http.php +++ b/includes/httpclient-2016-05-02/http.php @@ -17,2123 +17,2123 @@ class http_class { - var $host_name=""; - var $host_port=0; - var $proxy_host_name=""; - var $proxy_host_port=80; - var $socks_host_name = ''; - var $socks_host_port = 1080; - var $socks_version = '5'; + var $host_name=""; + var $host_port=0; + var $proxy_host_name=""; + var $proxy_host_port=80; + var $socks_host_name = ''; + var $socks_host_port = 1080; + var $socks_version = '5'; - var $protocol="http"; - var $request_method="GET"; - var $user_agent='httpclient (http://www.phpclasses.org/httpclient $Revision: 1.94 $)'; - var $accept=''; - var $authentication_mechanism=""; - var $user; - var $password; - var $realm; - var $workstation; - var $proxy_authentication_mechanism=""; - var $proxy_user; - var $proxy_password; - var $proxy_realm; - var $proxy_workstation; - var $request_uri=""; - var $request=""; - var $request_headers=array(); - var $request_user; - var $request_password; - var $request_realm; - var $request_workstation; - var $proxy_request_user; - var $proxy_request_password; - var $proxy_request_realm; - var $proxy_request_workstation; - var $request_body=""; - var $request_arguments=array(); - var $protocol_version="1.1"; - var $timeout=0; - var $data_timeout=0; - var $debug=0; - var $log_debug=0; - var $debug_response_body=1; - var $html_debug=0; - var $support_cookies=1; - var $cookies=array(); - var $error=""; - var $error_code = HTTP_CLIENT_ERROR_NO_ERROR; - var $exclude_address=""; - var $follow_redirect=0; - var $redirection_limit=5; - var $response_status=""; - var $response_message=""; - var $file_buffer_length=8000; - var $force_multipart_form_post=0; - var $prefer_curl = 0; - var $keep_alive = 1; - var $sasl_authenticate = 1; + var $protocol="http"; + var $request_method="GET"; + var $user_agent='httpclient (http://www.phpclasses.org/httpclient $Revision: 1.94 $)'; + var $accept=''; + var $authentication_mechanism=""; + var $user; + var $password; + var $realm; + var $workstation; + var $proxy_authentication_mechanism=""; + var $proxy_user; + var $proxy_password; + var $proxy_realm; + var $proxy_workstation; + var $request_uri=""; + var $request=""; + var $request_headers=array(); + var $request_user; + var $request_password; + var $request_realm; + var $request_workstation; + var $proxy_request_user; + var $proxy_request_password; + var $proxy_request_realm; + var $proxy_request_workstation; + var $request_body=""; + var $request_arguments=array(); + var $protocol_version="1.1"; + var $timeout=0; + var $data_timeout=0; + var $debug=0; + var $log_debug=0; + var $debug_response_body=1; + var $html_debug=0; + var $support_cookies=1; + var $cookies=array(); + var $error=""; + var $error_code = HTTP_CLIENT_ERROR_NO_ERROR; + var $exclude_address=""; + var $follow_redirect=0; + var $redirection_limit=5; + var $response_status=""; + var $response_message=""; + var $file_buffer_length=8000; + var $force_multipart_form_post=0; + var $prefer_curl = 0; + var $keep_alive = 1; + var $sasl_authenticate = 1; - /* private variables - DO NOT ACCESS */ + /* private variables - DO NOT ACCESS */ - var $state="Disconnected"; - var $use_curl=0; - var $connection=0; - var $content_length=0; - var $response=""; - var $read_response=0; - var $read_length=0; - var $request_host=""; - var $next_token=""; - var $redirection_level=0; - var $chunked=0; - var $remaining_chunk=0; - var $last_chunk_read=0; - var $months=array( - "Jan"=>"01", - "Feb"=>"02", - "Mar"=>"03", - "Apr"=>"04", - "May"=>"05", - "Jun"=>"06", - "Jul"=>"07", - "Aug"=>"08", - "Sep"=>"09", - "Oct"=>"10", - "Nov"=>"11", - "Dec"=>"12"); - var $session=''; - var $connection_close=0; - var $force_close = 0; - var $connected_host = ''; - var $connected_port = -1; - var $connected_ssl = 0; + var $state="Disconnected"; + var $use_curl=0; + var $connection=0; + var $content_length=0; + var $response=""; + var $read_response=0; + var $read_length=0; + var $request_host=""; + var $next_token=""; + var $redirection_level=0; + var $chunked=0; + var $remaining_chunk=0; + var $last_chunk_read=0; + var $months=array( + "Jan"=>"01", + "Feb"=>"02", + "Mar"=>"03", + "Apr"=>"04", + "May"=>"05", + "Jun"=>"06", + "Jul"=>"07", + "Aug"=>"08", + "Sep"=>"09", + "Oct"=>"10", + "Nov"=>"11", + "Dec"=>"12"); + var $session=''; + var $connection_close=0; + var $force_close = 0; + var $connected_host = ''; + var $connected_port = -1; + var $connected_ssl = 0; - /* Private methods - DO NOT CALL */ + /* Private methods - DO NOT CALL */ - Function Tokenize($string,$separator="") - { - if(!strcmp($separator,"")) - { - $separator=$string; - $string=$this->next_token; - } - for($character=0;$characternext_token=substr($string,$found+1); - return(substr($string,0,$found)); - } - else - { - $this->next_token=""; - return($string); - } - } + Function Tokenize($string,$separator="") + { + if(!strcmp($separator,"")) + { + $separator=$string; + $string=$this->next_token; + } + for($character=0;$characternext_token=substr($string,$found+1); + return(substr($string,0,$found)); + } + else + { + $this->next_token=""; + return($string); + } + } - Function CookieEncode($value, $name) - { - return($name ? str_replace("=", "%25", $value) : str_replace(";", "%3B", $value)); - } + Function CookieEncode($value, $name) + { + return($name ? str_replace("=", "%25", $value) : str_replace(";", "%3B", $value)); + } - Function SetError($error, $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR) - { - $this->error_code = $error_code; - return($this->error=$error); - } + Function SetError($error, $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR) + { + $this->error_code = $error_code; + return($this->error=$error); + } - Function SetPHPError($error, &$php_error_message, $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR) - { - if(IsSet($php_error_message) - && strlen($php_error_message)) - $error.=": ".$php_error_message; - return($this->SetError($error, $error_code)); - } + Function SetPHPError($error, &$php_error_message, $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR) + { + if(IsSet($php_error_message) + && strlen($php_error_message)) + $error.=": ".$php_error_message; + return($this->SetError($error, $error_code)); + } - Function SetDataAccessError($error,$check_connection=0) - { - $this->error=$error; - $this->error_code = HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE; - if(!$this->use_curl - && function_exists("socket_get_status")) - { - $status=socket_get_status($this->connection); - if($status["timed_out"]) - $this->error.=": data access time out"; - elseif($status["eof"]) - { - if($check_connection) - $this->error=""; - else - $this->error.=": the server disconnected"; - } - } - } + Function SetDataAccessError($error,$check_connection=0) + { + $this->error=$error; + $this->error_code = HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE; + if(!$this->use_curl + && function_exists("socket_get_status")) + { + $status=socket_get_status($this->connection); + if($status["timed_out"]) + $this->error.=": data access time out"; + elseif($status["eof"]) + { + if($check_connection) + $this->error=""; + else + $this->error.=": the server disconnected"; + } + } + } - Function OutputDebug($message) - { - if($this->log_debug) - { - if(strlen($this->log_file_name)) - error_log($message."\n", 3, $this->log_file_name); - else - error_log($message); - } - else - { - $message.="\n"; - if($this->html_debug) - $message=str_replace("\n","
\n",HtmlEntities($message)); - echo $message; - flush(); - } - } + Function OutputDebug($message) + { + if($this->log_debug) + { + if(strlen($this->log_file_name)) + error_log($message."\n", 3, $this->log_file_name); + else + error_log($message); + } + else + { + $message.="\n"; + if($this->html_debug) + $message=str_replace("\n","
\n",HtmlEntities($message)); + echo $message; + flush(); + } + } - Function GetLine() - { - for($line="";;) - { - if($this->use_curl) - { - $eol=strpos($this->response,"\n",$this->read_response); - $data=($eol ? substr($this->response,$this->read_response,$eol+1-$this->read_response) : ""); - $this->read_response+=strlen($data); - } - else - { - if(feof($this->connection)) - { - $this->SetDataAccessError("reached the end of data while reading from the HTTP server connection"); - return(0); - } - $data=fgets($this->connection,100); - } - if(GetType($data)!="string" - || strlen($data)==0) - { - $this->SetDataAccessError("it was not possible to read line from the HTTP server"); - return(0); - } - $line.=$data; - $length=strlen($line); - if($length - && !strcmp(substr($line,$length-1,1),"\n")) - { - $length-=(($length>=2 && !strcmp(substr($line,$length-2,1),"\r")) ? 2 : 1); - $line=substr($line,0,$length); - if($this->debug) - $this->OutputDebug("S $line"); - return($line); - } - } - } + Function GetLine() + { + for($line="";;) + { + if($this->use_curl) + { + $eol=strpos($this->response,"\n",$this->read_response); + $data=($eol ? substr($this->response,$this->read_response,$eol+1-$this->read_response) : ""); + $this->read_response+=strlen($data); + } + else + { + if(feof($this->connection)) + { + $this->SetDataAccessError("reached the end of data while reading from the HTTP server connection"); + return(0); + } + $data=fgets($this->connection,100); + } + if(GetType($data)!="string" + || strlen($data)==0) + { + $this->SetDataAccessError("it was not possible to read line from the HTTP server"); + return(0); + } + $line.=$data; + $length=strlen($line); + if($length + && !strcmp(substr($line,$length-1,1),"\n")) + { + $length-=(($length>=2 && !strcmp(substr($line,$length-2,1),"\r")) ? 2 : 1); + $line=substr($line,0,$length); + if($this->debug) + $this->OutputDebug("S $line"); + return($line); + } + } + } - Function PutLine($line) - { - if($this->debug) - $this->OutputDebug("C $line"); - if(!fputs($this->connection,$line."\r\n")) - { - $this->SetDataAccessError("it was not possible to send a line to the HTTP server"); - return(0); - } - return(1); - } + Function PutLine($line) + { + if($this->debug) + $this->OutputDebug("C $line"); + if(!fputs($this->connection,$line."\r\n")) + { + $this->SetDataAccessError("it was not possible to send a line to the HTTP server"); + return(0); + } + return(1); + } - Function PutData($data) - { - if(strlen($data)) - { - if($this->debug) - $this->OutputDebug('C '.$data); - if(!fputs($this->connection,$data)) - { - $this->SetDataAccessError("it was not possible to send data to the HTTP server"); - return(0); - } - } - return(1); - } + Function PutData($data) + { + if(strlen($data)) + { + if($this->debug) + $this->OutputDebug('C '.$data); + if(!fputs($this->connection,$data)) + { + $this->SetDataAccessError("it was not possible to send data to the HTTP server"); + return(0); + } + } + return(1); + } - Function FlushData() - { - if(!fflush($this->connection)) - { - $this->SetDataAccessError("it was not possible to send data to the HTTP server"); - return(0); - } - return(1); - } + Function FlushData() + { + if(!fflush($this->connection)) + { + $this->SetDataAccessError("it was not possible to send data to the HTTP server"); + return(0); + } + return(1); + } - Function ReadChunkSize() - { - if($this->remaining_chunk==0) - { - $debug=$this->debug; - if(!$this->debug_response_body) - $this->debug=0; - $line=$this->GetLine(); - $this->debug=$debug; - if(GetType($line)!="string") - return($this->SetError("could not read chunk start: ".$this->error, $this->error_code)); - $this->remaining_chunk=hexdec($line); - if($this->remaining_chunk == 0) - { - if(!$this->debug_response_body) - $this->debug=0; - $line=$this->GetLine(); - $this->debug=$debug; - if(GetType($line)!="string") - return($this->SetError("could not read chunk end: ".$this->error, $this->error_code)); - } - } - return(""); - } + Function ReadChunkSize() + { + if($this->remaining_chunk==0) + { + $debug=$this->debug; + if(!$this->debug_response_body) + $this->debug=0; + $line=$this->GetLine(); + $this->debug=$debug; + if(GetType($line)!="string") + return($this->SetError("could not read chunk start: ".$this->error, $this->error_code)); + $this->remaining_chunk=hexdec($line); + if($this->remaining_chunk == 0) + { + if(!$this->debug_response_body) + $this->debug=0; + $line=$this->GetLine(); + $this->debug=$debug; + if(GetType($line)!="string") + return($this->SetError("could not read chunk end: ".$this->error, $this->error_code)); + } + } + return(""); + } - Function ReadBytes($length) - { - if($this->use_curl) - { - $bytes=substr($this->response,$this->read_response,min($length,strlen($this->response)-$this->read_response)); - $this->read_response+=strlen($bytes); - if($this->debug - && $this->debug_response_body - && strlen($bytes)) - $this->OutputDebug("S ".$bytes); - } - else - { - if($this->chunked) - { - for($bytes="",$remaining=$length;$remaining;) - { - if(strlen($this->ReadChunkSize())) - return(""); - if($this->remaining_chunk==0) - { - $this->last_chunk_read=1; - break; - } - $ask=min($this->remaining_chunk,$remaining); - $chunk=@fread($this->connection,$ask); - $read=strlen($chunk); - if($read==0) - { - $this->SetDataAccessError("it was not possible to read data chunk from the HTTP server"); - return(""); - } - if($this->debug - && $this->debug_response_body) - $this->OutputDebug("S ".$chunk); - $bytes.=$chunk; - $this->remaining_chunk-=$read; - $remaining-=$read; - if($this->remaining_chunk==0) - { - if(feof($this->connection)) - return($this->SetError("reached the end of data while reading the end of data chunk mark from the HTTP server", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - $data=@fread($this->connection,2); - if(strcmp($data,"\r\n")) - { - $this->SetDataAccessError("it was not possible to read end of data chunk from the HTTP server"); - return(""); - } - } - } - } - else - { - $bytes=@fread($this->connection,$length); - if(strlen($bytes)) - { - if($this->debug - && $this->debug_response_body) - $this->OutputDebug("S ".$bytes); - } - else - $this->SetDataAccessError("it was not possible to read data from the HTTP server", $this->connection_close); - } - } - return($bytes); - } + Function ReadBytes($length) + { + if($this->use_curl) + { + $bytes=substr($this->response,$this->read_response,min($length,strlen($this->response)-$this->read_response)); + $this->read_response+=strlen($bytes); + if($this->debug + && $this->debug_response_body + && strlen($bytes)) + $this->OutputDebug("S ".$bytes); + } + else + { + if($this->chunked) + { + for($bytes="",$remaining=$length;$remaining;) + { + if(strlen($this->ReadChunkSize())) + return(""); + if($this->remaining_chunk==0) + { + $this->last_chunk_read=1; + break; + } + $ask=min($this->remaining_chunk,$remaining); + $chunk=@fread($this->connection,$ask); + $read=strlen($chunk); + if($read==0) + { + $this->SetDataAccessError("it was not possible to read data chunk from the HTTP server"); + return(""); + } + if($this->debug + && $this->debug_response_body) + $this->OutputDebug("S ".$chunk); + $bytes.=$chunk; + $this->remaining_chunk-=$read; + $remaining-=$read; + if($this->remaining_chunk==0) + { + if(feof($this->connection)) + return($this->SetError("reached the end of data while reading the end of data chunk mark from the HTTP server", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + $data=@fread($this->connection,2); + if(strcmp($data,"\r\n")) + { + $this->SetDataAccessError("it was not possible to read end of data chunk from the HTTP server"); + return(""); + } + } + } + } + else + { + $bytes=@fread($this->connection,$length); + if(strlen($bytes)) + { + if($this->debug + && $this->debug_response_body) + $this->OutputDebug("S ".$bytes); + } + else + $this->SetDataAccessError("it was not possible to read data from the HTTP server", $this->connection_close); + } + } + return($bytes); + } - Function EndOfInput() - { - if($this->use_curl) - return($this->read_response>=strlen($this->response)); - if($this->chunked) - return($this->last_chunk_read); - if($this->content_length_set) - return($this->content_length <= $this->read_length); - return(feof($this->connection)); - } + Function EndOfInput() + { + if($this->use_curl) + return($this->read_response>=strlen($this->response)); + if($this->chunked) + return($this->last_chunk_read); + if($this->content_length_set) + return($this->content_length <= $this->read_length); + return(feof($this->connection)); + } - Function Resolve($domain, &$ip, $server_type) - { - if(preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$domain)) - $ip=$domain; - else - { - if($this->debug) - $this->OutputDebug('Resolving '.$server_type.' server domain "'.$domain.'"...'); - if(!strcmp($ip=@gethostbyname($domain),$domain)) - $ip=""; - } - if(strlen($ip)==0 - || (strlen($this->exclude_address) - && !strcmp(@gethostbyname($this->exclude_address),$ip))) - return($this->SetError("could not resolve the host domain \"".$domain."\"", HTTP_CLIENT_ERROR_INVALID_SERVER_ADDRESS)); - return(''); - } + Function Resolve($domain, &$ip, $server_type) + { + if(preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$domain)) + $ip=$domain; + else + { + if($this->debug) + $this->OutputDebug('Resolving '.$server_type.' server domain "'.$domain.'"...'); + if(!strcmp($ip=@gethostbyname($domain),$domain)) + $ip=""; + } + if(strlen($ip)==0 + || (strlen($this->exclude_address) + && !strcmp(@gethostbyname($this->exclude_address),$ip))) + return($this->SetError("could not resolve the host domain \"".$domain."\"", HTTP_CLIENT_ERROR_INVALID_SERVER_ADDRESS)); + return(''); + } - Function Connect($host_name, $host_port, $ssl, $server_type = 'HTTP') - { - $domain=$host_name; - $port = $host_port; - if(strlen($error = $this->Resolve($domain, $ip, $server_type))) - return($error); - if(strlen($this->socks_host_name)) - { - switch($this->socks_version) - { - case '4': - $version = 4; - break; - case '5': - $version = 5; - break; - default: - return('it was not specified a supported SOCKS protocol version'); - break; - } - $host_ip = $ip; - $port = $this->socks_host_port; - $host_server_type = $server_type; - $server_type = 'SOCKS'; - if(strlen($error = $this->Resolve($this->socks_host_name, $ip, $server_type))) - return($error); - } - if($this->debug) - $this->OutputDebug('Connecting to '.$server_type.' server IP '.$ip.' port '.$port.'...'); - if($ssl) - $ip="ssl://".$host_name; - if(($this->connection=($this->timeout ? @fsockopen($ip, $port, $errno, $error, $this->timeout) : @fsockopen($ip, $port, $errno)))==0) - { - $error_code = HTTP_CLIENT_ERROR_CANNOT_CONNECT; - switch($errno) - { - case -3: - return($this->SetError("socket could not be created", $error_code)); - case -4: - return($this->SetError("dns lookup on hostname \"".$host_name."\" failed", $error_code)); - case -5: - return($this->SetError("connection refused or timed out", $error_code)); - case -6: - return($this->SetError("fdopen() call failed", $error_code)); - case -7: - return($this->SetError("setvbuf() call failed", $error_code)); - default: - return($this->SetPHPError($errno." could not connect to the host \"".$host_name."\"",$php_errormsg, $error_code)); - } - } - else - { - if($this->data_timeout - && function_exists("socket_set_timeout")) - socket_set_timeout($this->connection,$this->data_timeout,0); - if(strlen($this->socks_host_name)) - { - if($this->debug) - $this->OutputDebug('Connected to the SOCKS server '.$this->socks_host_name); - $send_error = 'it was not possible to send data to the SOCKS server'; - $receive_error = 'it was not possible to receive data from the SOCKS server'; - switch($version) - { - case 4: - $command = 1; - $user = ''; - if(!fputs($this->connection, chr($version).chr($command).pack('nN', $host_port, ip2long($host_ip)).$user.Chr(0))) - $error = $this->SetDataAccessError($send_error); - else - { - $response = fgets($this->connection, 9); - if(strlen($response) != 8) - $error = $this->SetDataAccessError($receive_error); - else - { - $socks_errors = array( - "\x5a"=>'', - "\x5b"=>'request rejected', - "\x5c"=>'request failed because client is not running identd (or not reachable from the server)', - "\x5d"=>'request failed because client\'s identd could not confirm the user ID string in the request', - ); - $error_code = $response[1]; - $error = (IsSet($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown'); - if(strlen($error)) - $error = 'SOCKS error: '.$error; - } - } - break; - case 5: - if($this->debug) - $this->OutputDebug('Negotiating the authentication method ...'); - $methods = 1; - $method = 0; - if(!fputs($this->connection, chr($version).chr($methods).chr($method))) - $error = $this->SetDataAccessError($send_error); - else - { - $response = fgets($this->connection, 3); - if(strlen($response) != 2) - $error = $this->SetDataAccessError($receive_error); - elseif(Ord($response[1]) != $method) - $error = 'the SOCKS server requires an authentication method that is not yet supported'; - else - { - if($this->debug) - $this->OutputDebug('Connecting to '.$host_server_type.' server IP '.$host_ip.' port '.$host_port.'...'); - $command = 1; - $address_type = 1; - if(!fputs($this->connection, chr($version).chr($command)."\x00".chr($address_type).pack('Nn', ip2long($host_ip), $host_port))) - $error = $this->SetDataAccessError($send_error); - else - { - $response = fgets($this->connection, 11); - if(strlen($response) != 10) - $error = $this->SetDataAccessError($receive_error); - else - { - $socks_errors = array( - "\x00"=>'', - "\x01"=>'general SOCKS server failure', - "\x02"=>'connection not allowed by ruleset', - "\x03"=>'Network unreachable', - "\x04"=>'Host unreachable', - "\x05"=>'Connection refused', - "\x06"=>'TTL expired', - "\x07"=>'Command not supported', - "\x08"=>'Address type not supported' - ); - $error_code = $response[1]; - $error = (IsSet($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown'); - if(strlen($error)) - $error = 'SOCKS error: '.$error; - } - } - } - } - break; - default: - $error = 'support for SOCKS protocol version '.$this->socks_version.' is not yet implemented'; - break; - } - if(strlen($error)) - { - fclose($this->connection); - return($error); - } - } - if($this->debug) - $this->OutputDebug("Connected to $host_name"); - if(strlen($this->proxy_host_name) - && !strcmp(strtolower($this->protocol), 'https')) - { - if(function_exists('stream_socket_enable_crypto') - && in_array('ssl', stream_get_transports())) - $this->state = "ConnectedToProxy"; - else - { - $this->OutputDebug("It is not possible to start SSL after connecting to the proxy server. If the proxy refuses to forward the SSL request, you may need to upgrade to PHP 5.1 or later with OpenSSL support enabled."); - $this->state="Connected"; - } - } - else - $this->state="Connected"; - return(""); - } - } + Function Connect($host_name, $host_port, $ssl, $server_type = 'HTTP') + { + $domain=$host_name; + $port = $host_port; + if(strlen($error = $this->Resolve($domain, $ip, $server_type))) + return($error); + if(strlen($this->socks_host_name)) + { + switch($this->socks_version) + { + case '4': + $version = 4; + break; + case '5': + $version = 5; + break; + default: + return('it was not specified a supported SOCKS protocol version'); + break; + } + $host_ip = $ip; + $port = $this->socks_host_port; + $host_server_type = $server_type; + $server_type = 'SOCKS'; + if(strlen($error = $this->Resolve($this->socks_host_name, $ip, $server_type))) + return($error); + } + if($this->debug) + $this->OutputDebug('Connecting to '.$server_type.' server IP '.$ip.' port '.$port.'...'); + if($ssl) + $ip="ssl://".$host_name; + if(($this->connection=($this->timeout ? @fsockopen($ip, $port, $errno, $error, $this->timeout) : @fsockopen($ip, $port, $errno)))==0) + { + $error_code = HTTP_CLIENT_ERROR_CANNOT_CONNECT; + switch($errno) + { + case -3: + return($this->SetError("socket could not be created", $error_code)); + case -4: + return($this->SetError("dns lookup on hostname \"".$host_name."\" failed", $error_code)); + case -5: + return($this->SetError("connection refused or timed out", $error_code)); + case -6: + return($this->SetError("fdopen() call failed", $error_code)); + case -7: + return($this->SetError("setvbuf() call failed", $error_code)); + default: + return($this->SetPHPError($errno." could not connect to the host \"".$host_name."\"",$php_errormsg, $error_code)); + } + } + else + { + if($this->data_timeout + && function_exists("socket_set_timeout")) + socket_set_timeout($this->connection,$this->data_timeout,0); + if(strlen($this->socks_host_name)) + { + if($this->debug) + $this->OutputDebug('Connected to the SOCKS server '.$this->socks_host_name); + $send_error = 'it was not possible to send data to the SOCKS server'; + $receive_error = 'it was not possible to receive data from the SOCKS server'; + switch($version) + { + case 4: + $command = 1; + $user = ''; + if(!fputs($this->connection, chr($version).chr($command).pack('nN', $host_port, ip2long($host_ip)).$user.Chr(0))) + $error = $this->SetDataAccessError($send_error); + else + { + $response = fgets($this->connection, 9); + if(strlen($response) != 8) + $error = $this->SetDataAccessError($receive_error); + else + { + $socks_errors = array( + "\x5a"=>'', + "\x5b"=>'request rejected', + "\x5c"=>'request failed because client is not running identd (or not reachable from the server)', + "\x5d"=>'request failed because client\'s identd could not confirm the user ID string in the request', + ); + $error_code = $response[1]; + $error = (IsSet($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown'); + if(strlen($error)) + $error = 'SOCKS error: '.$error; + } + } + break; + case 5: + if($this->debug) + $this->OutputDebug('Negotiating the authentication method ...'); + $methods = 1; + $method = 0; + if(!fputs($this->connection, chr($version).chr($methods).chr($method))) + $error = $this->SetDataAccessError($send_error); + else + { + $response = fgets($this->connection, 3); + if(strlen($response) != 2) + $error = $this->SetDataAccessError($receive_error); + elseif(Ord($response[1]) != $method) + $error = 'the SOCKS server requires an authentication method that is not yet supported'; + else + { + if($this->debug) + $this->OutputDebug('Connecting to '.$host_server_type.' server IP '.$host_ip.' port '.$host_port.'...'); + $command = 1; + $address_type = 1; + if(!fputs($this->connection, chr($version).chr($command)."\x00".chr($address_type).pack('Nn', ip2long($host_ip), $host_port))) + $error = $this->SetDataAccessError($send_error); + else + { + $response = fgets($this->connection, 11); + if(strlen($response) != 10) + $error = $this->SetDataAccessError($receive_error); + else + { + $socks_errors = array( + "\x00"=>'', + "\x01"=>'general SOCKS server failure', + "\x02"=>'connection not allowed by ruleset', + "\x03"=>'Network unreachable', + "\x04"=>'Host unreachable', + "\x05"=>'Connection refused', + "\x06"=>'TTL expired', + "\x07"=>'Command not supported', + "\x08"=>'Address type not supported' + ); + $error_code = $response[1]; + $error = (IsSet($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown'); + if(strlen($error)) + $error = 'SOCKS error: '.$error; + } + } + } + } + break; + default: + $error = 'support for SOCKS protocol version '.$this->socks_version.' is not yet implemented'; + break; + } + if(strlen($error)) + { + fclose($this->connection); + return($error); + } + } + if($this->debug) + $this->OutputDebug("Connected to $host_name"); + if(strlen($this->proxy_host_name) + && !strcmp(strtolower($this->protocol), 'https')) + { + if(function_exists('stream_socket_enable_crypto') + && in_array('ssl', stream_get_transports())) + $this->state = "ConnectedToProxy"; + else + { + $this->OutputDebug("It is not possible to start SSL after connecting to the proxy server. If the proxy refuses to forward the SSL request, you may need to upgrade to PHP 5.1 or later with OpenSSL support enabled."); + $this->state="Connected"; + } + } + else + $this->state="Connected"; + return(""); + } + } - Function Disconnect() - { - if($this->debug) - $this->OutputDebug("Disconnected from ".$this->connected_host); - if($this->use_curl) - { - curl_close($this->connection); - $this->response=""; - } - else - fclose($this->connection); - $this->state="Disconnected"; - return(""); - } + Function Disconnect() + { + if($this->debug) + $this->OutputDebug("Disconnected from ".$this->connected_host); + if($this->use_curl) + { + curl_close($this->connection); + $this->response=""; + } + else + fclose($this->connection); + $this->state="Disconnected"; + return(""); + } - /* Public methods */ + /* Public methods */ - Function GetRequestArguments($url, &$arguments) - { - $this->error = ''; - $this->error_code = HTTP_CLIENT_ERROR_NO_ERROR; - $arguments=array(); - $url = str_replace(' ', '%20', $url); - $parameters=@parse_url($url); - if(!$parameters) - return($this->SetError("it was not specified a valid URL", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - if(!IsSet($parameters["scheme"])) - return($this->SetError("it was not specified the protocol type argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - switch(strtolower($parameters["scheme"])) - { - case "http": - case "https": - $arguments["Protocol"]=$parameters["scheme"]; - break; - default: - return($parameters["scheme"]." connection scheme is not yet supported"); - } - if(!IsSet($parameters["host"])) - return($this->SetError("it was not specified the connection host argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $arguments["HostName"]=$parameters["host"]; - $arguments["Headers"]=array("Host"=>$parameters["host"].(IsSet($parameters["port"]) ? ":".$parameters["port"] : "")); - if(IsSet($parameters["user"])) - { - $arguments["AuthUser"]=UrlDecode($parameters["user"]); - if(!IsSet($parameters["pass"])) - $arguments["AuthPassword"]=""; - } - if(IsSet($parameters["pass"])) - { - if(!IsSet($parameters["user"])) - $arguments["AuthUser"]=""; - $arguments["AuthPassword"]=UrlDecode($parameters["pass"]); - } - if(IsSet($parameters["port"])) - { - if(strcmp($parameters["port"],strval(intval($parameters["port"])))) - return($this->SetError("it was not specified a valid connection host argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $arguments["HostPort"]=intval($parameters["port"]); - } - else - $arguments["HostPort"]=0; - $arguments["RequestURI"]=(IsSet($parameters["path"]) ? $parameters["path"] : "/").(IsSet($parameters["query"]) ? "?".$parameters["query"] : ""); - if(strlen($this->user_agent)) - $arguments["Headers"]["User-Agent"]=$this->user_agent; - if(strlen($this->accept)) - $arguments["Headers"]["Accept"]=$this->accept; - return(""); - } + Function GetRequestArguments($url, &$arguments) + { + $this->error = ''; + $this->error_code = HTTP_CLIENT_ERROR_NO_ERROR; + $arguments=array(); + $url = str_replace(' ', '%20', $url); + $parameters=@parse_url($url); + if(!$parameters) + return($this->SetError("it was not specified a valid URL", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + if(!IsSet($parameters["scheme"])) + return($this->SetError("it was not specified the protocol type argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + switch(strtolower($parameters["scheme"])) + { + case "http": + case "https": + $arguments["Protocol"]=$parameters["scheme"]; + break; + default: + return($parameters["scheme"]." connection scheme is not yet supported"); + } + if(!IsSet($parameters["host"])) + return($this->SetError("it was not specified the connection host argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $arguments["HostName"]=$parameters["host"]; + $arguments["Headers"]=array("Host"=>$parameters["host"].(IsSet($parameters["port"]) ? ":".$parameters["port"] : "")); + if(IsSet($parameters["user"])) + { + $arguments["AuthUser"]=UrlDecode($parameters["user"]); + if(!IsSet($parameters["pass"])) + $arguments["AuthPassword"]=""; + } + if(IsSet($parameters["pass"])) + { + if(!IsSet($parameters["user"])) + $arguments["AuthUser"]=""; + $arguments["AuthPassword"]=UrlDecode($parameters["pass"]); + } + if(IsSet($parameters["port"])) + { + if(strcmp($parameters["port"],strval(intval($parameters["port"])))) + return($this->SetError("it was not specified a valid connection host argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $arguments["HostPort"]=intval($parameters["port"]); + } + else + $arguments["HostPort"]=0; + $arguments["RequestURI"]=(IsSet($parameters["path"]) ? $parameters["path"] : "/").(IsSet($parameters["query"]) ? "?".$parameters["query"] : ""); + if(strlen($this->user_agent)) + $arguments["Headers"]["User-Agent"]=$this->user_agent; + if(strlen($this->accept)) + $arguments["Headers"]["Accept"]=$this->accept; + return(""); + } - Function Open($arguments) - { - if(strlen($this->error)) - return($this->error); - $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR; - if(IsSet($arguments["HostName"])) - $this->host_name=$arguments["HostName"]; - if(IsSet($arguments["HostPort"])) - $this->host_port=$arguments["HostPort"]; - if(IsSet($arguments["ProxyHostName"])) - $this->proxy_host_name=$arguments["ProxyHostName"]; - if(IsSet($arguments["ProxyHostPort"])) - $this->proxy_host_port=$arguments["ProxyHostPort"]; - if(IsSet($arguments["SOCKSHostName"])) - $this->socks_host_name=$arguments["SOCKSHostName"]; - if(IsSet($arguments["SOCKSHostPort"])) - $this->socks_host_port=$arguments["SOCKSHostPort"]; - if(IsSet($arguments["SOCKSVersion"])) - $this->socks_version=$arguments["SOCKSVersion"]; - if(IsSet($arguments["PreferCurl"])) - $this->prefer_curl=$arguments["PreferCurl"]; - if(IsSet($arguments["Protocol"])) - $this->protocol=$arguments["Protocol"]; - switch(strtolower($this->protocol)) - { - case "http": - $default_port=80; - break; - case "https": - $default_port=443; - break; - default: - return($this->SetError("it was not specified a valid connection protocol", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - } - if(strlen($this->proxy_host_name)==0) - { - if(strlen($this->host_name)==0) - return($this->SetError("it was not specified a valid hostname", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $host_name=$this->host_name; - $host_port=($this->host_port ? $this->host_port : $default_port); - $server_type = 'HTTP'; - } - else - { - $host_name=$this->proxy_host_name; - $host_port=$this->proxy_host_port; - $server_type = 'HTTP proxy'; - } - $ssl=(strtolower($this->protocol)=="https" && strlen($this->proxy_host_name)==0); - if($ssl - && strlen($this->socks_host_name)) - return($this->SetError('establishing SSL connections via a SOCKS server is not yet supported', HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $this->use_curl=($ssl && $this->prefer_curl && function_exists("curl_init")); - switch($this->state) - { - case 'Connected': - if(!strcmp($host_name, $this->connected_host) - && intval($host_port) == $this->connected_port - && intval($ssl) == $this->connected_ssl) - { - if($this->debug) - $this->OutputDebug("Reusing connection to ".$this->connected_host); - return(''); - } - if(strlen($error = $this->Disconnect())) - return($error); - case "Disconnected": - break; - default: - return("1 already connected"); - } - if($this->debug) - $this->OutputDebug("Connecting to ".$this->host_name); - if($this->use_curl) - { - $error=(($this->connection=curl_init($this->protocol."://".$this->host_name.($host_port==$default_port ? "" : ":".strval($host_port))."/")) ? "" : "Could not initialize a CURL session"); - if(strlen($error)==0) - { - if(IsSet($arguments["SSLCertificateFile"])) - curl_setopt($this->connection,CURLOPT_SSLCERT,$arguments["SSLCertificateFile"]); - if(IsSet($arguments["SSLCertificatePassword"])) - curl_setopt($this->connection,CURLOPT_SSLCERTPASSWD,$arguments["SSLCertificatePassword"]); - if(IsSet($arguments["SSLKeyFile"])) - curl_setopt($this->connection,CURLOPT_SSLKEY,$arguments["SSLKeyFile"]); - if(IsSet($arguments["SSLKeyPassword"])) - curl_setopt($this->connection,CURLOPT_SSLKEYPASSWD,$arguments["SSLKeyPassword"]); - } - $this->state="Connected"; - } - else - { - $error=""; - if(strlen($this->proxy_host_name) - && (IsSet($arguments["SSLCertificateFile"]) - || IsSet($arguments["SSLCertificateFile"]))) - $error="establishing SSL connections using certificates or private keys via non-SSL proxies is not supported"; - else - { - if($ssl) - { - if(IsSet($arguments["SSLCertificateFile"])) - $error="establishing SSL connections using certificates is only supported when the cURL extension is enabled"; - elseif(IsSet($arguments["SSLKeyFile"])) - $error="establishing SSL connections using a private key is only supported when the cURL extension is enabled"; - else - { - $version=explode(".",function_exists("phpversion") ? phpversion() : "3.0.7"); - $php_version=intval($version[0])*1000000+intval($version[1])*1000+intval($version[2]); - if($php_version<4003000) - $error="establishing SSL connections requires at least PHP version 4.3.0 or having the cURL extension enabled"; - elseif(!function_exists("extension_loaded") - || !extension_loaded("openssl")) - $error="establishing SSL connections requires the OpenSSL extension enabled"; - } - } - if(strlen($error)==0) - { - $error=$this->Connect($host_name, $host_port, $ssl, $server_type); - $error_code = $this->error_code; - } - } - } - if(strlen($error)) - return($this->SetError($error, $error_code)); - $this->session=md5(uniqid("")); - $this->connected_host = $host_name; - $this->connected_port = intval($host_port); - $this->connected_ssl = intval($ssl); - return(""); - } + Function Open($arguments) + { + if(strlen($this->error)) + return($this->error); + $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR; + if(IsSet($arguments["HostName"])) + $this->host_name=$arguments["HostName"]; + if(IsSet($arguments["HostPort"])) + $this->host_port=$arguments["HostPort"]; + if(IsSet($arguments["ProxyHostName"])) + $this->proxy_host_name=$arguments["ProxyHostName"]; + if(IsSet($arguments["ProxyHostPort"])) + $this->proxy_host_port=$arguments["ProxyHostPort"]; + if(IsSet($arguments["SOCKSHostName"])) + $this->socks_host_name=$arguments["SOCKSHostName"]; + if(IsSet($arguments["SOCKSHostPort"])) + $this->socks_host_port=$arguments["SOCKSHostPort"]; + if(IsSet($arguments["SOCKSVersion"])) + $this->socks_version=$arguments["SOCKSVersion"]; + if(IsSet($arguments["PreferCurl"])) + $this->prefer_curl=$arguments["PreferCurl"]; + if(IsSet($arguments["Protocol"])) + $this->protocol=$arguments["Protocol"]; + switch(strtolower($this->protocol)) + { + case "http": + $default_port=80; + break; + case "https": + $default_port=443; + break; + default: + return($this->SetError("it was not specified a valid connection protocol", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + } + if(strlen($this->proxy_host_name)==0) + { + if(strlen($this->host_name)==0) + return($this->SetError("it was not specified a valid hostname", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $host_name=$this->host_name; + $host_port=($this->host_port ? $this->host_port : $default_port); + $server_type = 'HTTP'; + } + else + { + $host_name=$this->proxy_host_name; + $host_port=$this->proxy_host_port; + $server_type = 'HTTP proxy'; + } + $ssl=(strtolower($this->protocol)=="https" && strlen($this->proxy_host_name)==0); + if($ssl + && strlen($this->socks_host_name)) + return($this->SetError('establishing SSL connections via a SOCKS server is not yet supported', HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $this->use_curl=($ssl && $this->prefer_curl && function_exists("curl_init")); + switch($this->state) + { + case 'Connected': + if(!strcmp($host_name, $this->connected_host) + && intval($host_port) == $this->connected_port + && intval($ssl) == $this->connected_ssl) + { + if($this->debug) + $this->OutputDebug("Reusing connection to ".$this->connected_host); + return(''); + } + if(strlen($error = $this->Disconnect())) + return($error); + case "Disconnected": + break; + default: + return("1 already connected"); + } + if($this->debug) + $this->OutputDebug("Connecting to ".$this->host_name); + if($this->use_curl) + { + $error=(($this->connection=curl_init($this->protocol."://".$this->host_name.($host_port==$default_port ? "" : ":".strval($host_port))."/")) ? "" : "Could not initialize a CURL session"); + if(strlen($error)==0) + { + if(IsSet($arguments["SSLCertificateFile"])) + curl_setopt($this->connection,CURLOPT_SSLCERT,$arguments["SSLCertificateFile"]); + if(IsSet($arguments["SSLCertificatePassword"])) + curl_setopt($this->connection,CURLOPT_SSLCERTPASSWD,$arguments["SSLCertificatePassword"]); + if(IsSet($arguments["SSLKeyFile"])) + curl_setopt($this->connection,CURLOPT_SSLKEY,$arguments["SSLKeyFile"]); + if(IsSet($arguments["SSLKeyPassword"])) + curl_setopt($this->connection,CURLOPT_SSLKEYPASSWD,$arguments["SSLKeyPassword"]); + } + $this->state="Connected"; + } + else + { + $error=""; + if(strlen($this->proxy_host_name) + && (IsSet($arguments["SSLCertificateFile"]) + || IsSet($arguments["SSLCertificateFile"]))) + $error="establishing SSL connections using certificates or private keys via non-SSL proxies is not supported"; + else + { + if($ssl) + { + if(IsSet($arguments["SSLCertificateFile"])) + $error="establishing SSL connections using certificates is only supported when the cURL extension is enabled"; + elseif(IsSet($arguments["SSLKeyFile"])) + $error="establishing SSL connections using a private key is only supported when the cURL extension is enabled"; + else + { + $version=explode(".",function_exists("phpversion") ? phpversion() : "3.0.7"); + $php_version=intval($version[0])*1000000+intval($version[1])*1000+intval($version[2]); + if($php_version<4003000) + $error="establishing SSL connections requires at least PHP version 4.3.0 or having the cURL extension enabled"; + elseif(!function_exists("extension_loaded") + || !extension_loaded("openssl")) + $error="establishing SSL connections requires the OpenSSL extension enabled"; + } + } + if(strlen($error)==0) + { + $error=$this->Connect($host_name, $host_port, $ssl, $server_type); + $error_code = $this->error_code; + } + } + } + if(strlen($error)) + return($this->SetError($error, $error_code)); + $this->session=md5(uniqid("")); + $this->connected_host = $host_name; + $this->connected_port = intval($host_port); + $this->connected_ssl = intval($ssl); + return(""); + } - Function Close($force = 0) - { - if($this->state=="Disconnected") - return("1 already disconnected"); - if(!$this->force_close - && $this->keep_alive - && !$force - && $this->state == 'ResponseReceived') - { - if($this->debug) - $this->OutputDebug('Keeping the connection alive to '.$this->connected_host); - $this->state = 'Connected'; - return(''); - } - return($this->Disconnect()); - } + Function Close($force = 0) + { + if($this->state=="Disconnected") + return("1 already disconnected"); + if(!$this->force_close + && $this->keep_alive + && !$force + && $this->state == 'ResponseReceived') + { + if($this->debug) + $this->OutputDebug('Keeping the connection alive to '.$this->connected_host); + $this->state = 'Connected'; + return(''); + } + return($this->Disconnect()); + } - Function PickCookies(&$cookies,$secure) - { - if(IsSet($this->cookies[$secure])) - { - $now=gmdate("Y-m-d H-i-s"); - for($domain=0,Reset($this->cookies[$secure]);$domaincookies[$secure]);Next($this->cookies[$secure]),$domain++) - { - $domain_pattern=Key($this->cookies[$secure]); - $match=strlen($this->request_host)-strlen($domain_pattern); - if($match>=0 - && !strcmp($domain_pattern,substr($this->request_host,$match)) - && ($match==0 - || $domain_pattern[0]=="." - || $this->request_host[$match-1]==".")) - { - for(Reset($this->cookies[$secure][$domain_pattern]),$path_part=0;$path_partcookies[$secure][$domain_pattern]);Next($this->cookies[$secure][$domain_pattern]),$path_part++) - { - $path=Key($this->cookies[$secure][$domain_pattern]); - if(strlen($this->request_uri)>=strlen($path) - && substr($this->request_uri,0,strlen($path))==$path) - { - for(Reset($this->cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookiecookies[$secure][$domain_pattern][$path]);Next($this->cookies[$secure][$domain_pattern][$path]),$cookie++) - { - $cookie_name=Key($this->cookies[$secure][$domain_pattern][$path]); - $expires=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]["expires"]; - if($expires=="" - || strcmp($now,$expires)<0) - $cookies[$cookie_name]=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]; - } - } - } - } - } - } - } + Function PickCookies(&$cookies,$secure) + { + if(IsSet($this->cookies[$secure])) + { + $now=gmdate("Y-m-d H-i-s"); + for($domain=0,Reset($this->cookies[$secure]);$domaincookies[$secure]);Next($this->cookies[$secure]),$domain++) + { + $domain_pattern=Key($this->cookies[$secure]); + $match=strlen($this->request_host)-strlen($domain_pattern); + if($match>=0 + && !strcmp($domain_pattern,substr($this->request_host,$match)) + && ($match==0 + || $domain_pattern[0]=="." + || $this->request_host[$match-1]==".")) + { + for(Reset($this->cookies[$secure][$domain_pattern]),$path_part=0;$path_partcookies[$secure][$domain_pattern]);Next($this->cookies[$secure][$domain_pattern]),$path_part++) + { + $path=Key($this->cookies[$secure][$domain_pattern]); + if(strlen($this->request_uri)>=strlen($path) + && substr($this->request_uri,0,strlen($path))==$path) + { + for(Reset($this->cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookiecookies[$secure][$domain_pattern][$path]);Next($this->cookies[$secure][$domain_pattern][$path]),$cookie++) + { + $cookie_name=Key($this->cookies[$secure][$domain_pattern][$path]); + $expires=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]["expires"]; + if($expires=="" + || strcmp($now,$expires)<0) + $cookies[$cookie_name]=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]; + } + } + } + } + } + } + } - Function GetFileDefinition($file, &$definition) - { - $name=""; - if(IsSet($file["FileName"])) - $name=basename($file["FileName"]); - if(IsSet($file["Name"])) - $name=$file["Name"]; - if(strlen($name)==0) - return("it was not specified the file part name"); - if(IsSet($file["Content-Type"])) - { - $content_type=$file["Content-Type"]; - $type=$this->Tokenize(strtolower($content_type),"/"); - $sub_type=$this->Tokenize(""); - switch($type) - { - case "text": - case "image": - case "audio": - case "video": - case "application": - case "message": - break; - case "automatic": - switch($sub_type) - { - case "name": - switch(GetType($dot=strrpos($name,"."))=="integer" ? strtolower(substr($name,$dot)) : "") - { - case ".xls": - $content_type="application/excel"; - break; - case ".hqx": - $content_type="application/macbinhex40"; - break; - case ".doc": - case ".dot": - case ".wrd": - $content_type="application/msword"; - break; - case ".pdf": - $content_type="application/pdf"; - break; - case ".pgp": - $content_type="application/pgp"; - break; - case ".ps": - case ".eps": - case ".ai": - $content_type="application/postscript"; - break; - case ".ppt": - $content_type="application/powerpoint"; - break; - case ".rtf": - $content_type="application/rtf"; - break; - case ".tgz": - case ".gtar": - $content_type="application/x-gtar"; - break; - case ".gz": - $content_type="application/x-gzip"; - break; - case ".php": - case ".php3": - $content_type="application/x-httpd-php"; - break; - case ".js": - $content_type="application/x-javascript"; - break; - case ".ppd": - case ".psd": - $content_type="application/x-photoshop"; - break; - case ".swf": - case ".swc": - case ".rf": - $content_type="application/x-shockwave-flash"; - break; - case ".tar": - $content_type="application/x-tar"; - break; - case ".zip": - $content_type="application/zip"; - break; - case ".mid": - case ".midi": - case ".kar": - $content_type="audio/midi"; - break; - case ".mp2": - case ".mp3": - case ".mpga": - $content_type="audio/mpeg"; - break; - case ".ra": - $content_type="audio/x-realaudio"; - break; - case ".wav": - $content_type="audio/wav"; - break; - case ".bmp": - $content_type="image/bitmap"; - break; - case ".gif": - $content_type="image/gif"; - break; - case ".iff": - $content_type="image/iff"; - break; - case ".jb2": - $content_type="image/jb2"; - break; - case ".jpg": - case ".jpe": - case ".jpeg": - $content_type="image/jpeg"; - break; - case ".jpx": - $content_type="image/jpx"; - break; - case ".png": - $content_type="image/png"; - break; - case ".tif": - case ".tiff": - $content_type="image/tiff"; - break; - case ".wbmp": - $content_type="image/vnd.wap.wbmp"; - break; - case ".xbm": - $content_type="image/xbm"; - break; - case ".css": - $content_type="text/css"; - break; - case ".txt": - $content_type="text/plain"; - break; - case ".htm": - case ".html": - $content_type="text/html"; - break; - case ".xml": - $content_type="text/xml"; - break; - case ".mpg": - case ".mpe": - case ".mpeg": - $content_type="video/mpeg"; - break; - case ".qt": - case ".mov": - $content_type="video/quicktime"; - break; - case ".avi": - $content_type="video/x-ms-video"; - break; - case ".eml": - $content_type="message/rfc822"; - break; - default: - $content_type="application/octet-stream"; - break; - } - break; - default: - return($content_type." is not a supported automatic content type detection method"); - } - break; - default: - return($content_type." is not a supported file content type"); - } - } - else - $content_type="application/octet-stream"; - $definition=array( - "Content-Type"=>$content_type, - "NAME"=>$name - ); - if(IsSet($file["FileName"])) - { - if(GetType($length=@filesize($file["FileName"]))!="integer") - { - $error="it was not possible to determine the length of the file ".$file["FileName"]; - if(IsSet($php_errormsg) - && strlen($php_errormsg)) - $error.=": ".$php_errormsg; - if(!file_exists($file["FileName"])) - $error="it was not possible to access the file ".$file["FileName"]; - return($error); - } - $definition["FILENAME"]=$file["FileName"]; - $definition["Content-Length"]=$length; - } - elseif(IsSet($file["Data"])) - $definition["Content-Length"]=strlen($definition["DATA"]=$file["Data"]); - else - return("it was not specified a valid file name"); - return(""); - } + Function GetFileDefinition($file, &$definition) + { + $name=""; + if(IsSet($file["FileName"])) + $name=basename($file["FileName"]); + if(IsSet($file["Name"])) + $name=$file["Name"]; + if(strlen($name)==0) + return("it was not specified the file part name"); + if(IsSet($file["Content-Type"])) + { + $content_type=$file["Content-Type"]; + $type=$this->Tokenize(strtolower($content_type),"/"); + $sub_type=$this->Tokenize(""); + switch($type) + { + case "text": + case "image": + case "audio": + case "video": + case "application": + case "message": + break; + case "automatic": + switch($sub_type) + { + case "name": + switch(GetType($dot=strrpos($name,"."))=="integer" ? strtolower(substr($name,$dot)) : "") + { + case ".xls": + $content_type="application/excel"; + break; + case ".hqx": + $content_type="application/macbinhex40"; + break; + case ".doc": + case ".dot": + case ".wrd": + $content_type="application/msword"; + break; + case ".pdf": + $content_type="application/pdf"; + break; + case ".pgp": + $content_type="application/pgp"; + break; + case ".ps": + case ".eps": + case ".ai": + $content_type="application/postscript"; + break; + case ".ppt": + $content_type="application/powerpoint"; + break; + case ".rtf": + $content_type="application/rtf"; + break; + case ".tgz": + case ".gtar": + $content_type="application/x-gtar"; + break; + case ".gz": + $content_type="application/x-gzip"; + break; + case ".php": + case ".php3": + $content_type="application/x-httpd-php"; + break; + case ".js": + $content_type="application/x-javascript"; + break; + case ".ppd": + case ".psd": + $content_type="application/x-photoshop"; + break; + case ".swf": + case ".swc": + case ".rf": + $content_type="application/x-shockwave-flash"; + break; + case ".tar": + $content_type="application/x-tar"; + break; + case ".zip": + $content_type="application/zip"; + break; + case ".mid": + case ".midi": + case ".kar": + $content_type="audio/midi"; + break; + case ".mp2": + case ".mp3": + case ".mpga": + $content_type="audio/mpeg"; + break; + case ".ra": + $content_type="audio/x-realaudio"; + break; + case ".wav": + $content_type="audio/wav"; + break; + case ".bmp": + $content_type="image/bitmap"; + break; + case ".gif": + $content_type="image/gif"; + break; + case ".iff": + $content_type="image/iff"; + break; + case ".jb2": + $content_type="image/jb2"; + break; + case ".jpg": + case ".jpe": + case ".jpeg": + $content_type="image/jpeg"; + break; + case ".jpx": + $content_type="image/jpx"; + break; + case ".png": + $content_type="image/png"; + break; + case ".tif": + case ".tiff": + $content_type="image/tiff"; + break; + case ".wbmp": + $content_type="image/vnd.wap.wbmp"; + break; + case ".xbm": + $content_type="image/xbm"; + break; + case ".css": + $content_type="text/css"; + break; + case ".txt": + $content_type="text/plain"; + break; + case ".htm": + case ".html": + $content_type="text/html"; + break; + case ".xml": + $content_type="text/xml"; + break; + case ".mpg": + case ".mpe": + case ".mpeg": + $content_type="video/mpeg"; + break; + case ".qt": + case ".mov": + $content_type="video/quicktime"; + break; + case ".avi": + $content_type="video/x-ms-video"; + break; + case ".eml": + $content_type="message/rfc822"; + break; + default: + $content_type="application/octet-stream"; + break; + } + break; + default: + return($content_type." is not a supported automatic content type detection method"); + } + break; + default: + return($content_type." is not a supported file content type"); + } + } + else + $content_type="application/octet-stream"; + $definition=array( + "Content-Type"=>$content_type, + "NAME"=>$name + ); + if(IsSet($file["FileName"])) + { + if(GetType($length=@filesize($file["FileName"]))!="integer") + { + $error="it was not possible to determine the length of the file ".$file["FileName"]; + if(IsSet($php_errormsg) + && strlen($php_errormsg)) + $error.=": ".$php_errormsg; + if(!file_exists($file["FileName"])) + $error="it was not possible to access the file ".$file["FileName"]; + return($error); + } + $definition["FILENAME"]=$file["FileName"]; + $definition["Content-Length"]=$length; + } + elseif(IsSet($file["Data"])) + $definition["Content-Length"]=strlen($definition["DATA"]=$file["Data"]); + else + return("it was not specified a valid file name"); + return(""); + } - Function ConnectFromProxy($arguments, &$headers) - { - $host = $this->host_name.':'.($this->host_port ? $this->host_port : 443); - $this->OutputDebug('Connecting from proxy to host '.$host); - if(!$this->PutLine('CONNECT '.$host.' HTTP/1.0') - || (strlen($this->user_agent) - && !$this->PutLine('User-Agent: '.$this->user_agent)) - || (strlen($this->accept) - && !$this->PutLine('Accept: '.$this->accept)) - || (IsSet($arguments['Headers']['Proxy-Authorization']) - && !$this->PutLine('Proxy-Authorization: '.$arguments['Headers']['Proxy-Authorization'])) - || !$this->PutLine('')) - { - $this->Disconnect(); - return($this->error); - } - $this->state = "ConnectSent"; - if(strlen($error=$this->ReadReplyHeadersResponse($headers))) - return($error); - $proxy_authorization=""; - while(!strcmp($this->response_status, "100")) - { - $this->state="ConnectSent"; - if(strlen($error=$this->ReadReplyHeadersResponse($headers))) - return($error); - } - switch($this->response_status) - { - case "200": - $this->OutputDebug('Establishing the cryptography layer with host '.$host); - if(!stream_socket_enable_crypto($this->connection, 1, STREAM_CRYPTO_METHOD_SSLv23_CLIENT)) - { - $this->OutputDebug('Failed establishing the cryptography layer with host '.$host); - $this->SetPHPError('it was not possible to start a SSL encrypted connection via this proxy', $php_errormsg, HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE); - $this->Disconnect(); - return($this->error); - } - $this->OutputDebug('Succeeded establishing the cryptography layer with host '.$host); - $this->state = "Connected"; - break; - case "407": - if(strlen($error=$this->Authenticate($headers, -1, $proxy_authorization, $this->proxy_request_user, $this->proxy_request_password, $this->proxy_request_realm, $this->proxy_request_workstation))) - return($error); - break; - default: - return($this->SetError("unable to send request via proxy", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - } - return(""); - } + Function ConnectFromProxy($arguments, &$headers) + { + $host = $this->host_name.':'.($this->host_port ? $this->host_port : 443); + $this->OutputDebug('Connecting from proxy to host '.$host); + if(!$this->PutLine('CONNECT '.$host.' HTTP/1.0') + || (strlen($this->user_agent) + && !$this->PutLine('User-Agent: '.$this->user_agent)) + || (strlen($this->accept) + && !$this->PutLine('Accept: '.$this->accept)) + || (IsSet($arguments['Headers']['Proxy-Authorization']) + && !$this->PutLine('Proxy-Authorization: '.$arguments['Headers']['Proxy-Authorization'])) + || !$this->PutLine('')) + { + $this->Disconnect(); + return($this->error); + } + $this->state = "ConnectSent"; + if(strlen($error=$this->ReadReplyHeadersResponse($headers))) + return($error); + $proxy_authorization=""; + while(!strcmp($this->response_status, "100")) + { + $this->state="ConnectSent"; + if(strlen($error=$this->ReadReplyHeadersResponse($headers))) + return($error); + } + switch($this->response_status) + { + case "200": + $this->OutputDebug('Establishing the cryptography layer with host '.$host); + if(!stream_socket_enable_crypto($this->connection, 1, STREAM_CRYPTO_METHOD_SSLv23_CLIENT)) + { + $this->OutputDebug('Failed establishing the cryptography layer with host '.$host); + $this->SetPHPError('it was not possible to start a SSL encrypted connection via this proxy', $php_errormsg, HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE); + $this->Disconnect(); + return($this->error); + } + $this->OutputDebug('Succeeded establishing the cryptography layer with host '.$host); + $this->state = "Connected"; + break; + case "407": + if(strlen($error=$this->Authenticate($headers, -1, $proxy_authorization, $this->proxy_request_user, $this->proxy_request_password, $this->proxy_request_realm, $this->proxy_request_workstation))) + return($error); + break; + default: + return($this->SetError("unable to send request via proxy", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + } + return(""); + } - Function SendRequest($arguments) - { - if(strlen($this->error)) - return($this->error); - if(IsSet($arguments["ProxyUser"])) - $this->proxy_request_user=$arguments["ProxyUser"]; - elseif(IsSet($this->proxy_user)) - $this->proxy_request_user=$this->proxy_user; - if(IsSet($arguments["ProxyPassword"])) - $this->proxy_request_password=$arguments["ProxyPassword"]; - elseif(IsSet($this->proxy_password)) - $this->proxy_request_password=$this->proxy_password; - if(IsSet($arguments["ProxyRealm"])) - $this->proxy_request_realm=$arguments["ProxyRealm"]; - elseif(IsSet($this->proxy_realm)) - $this->proxy_request_realm=$this->proxy_realm; - if(IsSet($arguments["ProxyWorkstation"])) - $this->proxy_request_workstation=$arguments["ProxyWorkstation"]; - elseif(IsSet($this->proxy_workstation)) - $this->proxy_request_workstation=$this->proxy_workstation; - switch($this->state) - { - case "Disconnected": - return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "Connected": - $connect = 0; - break; - case "ConnectedToProxy": - if(strlen($error = $this->ConnectFromProxy($arguments, $headers))) - return($error); - $connect = 1; - break; - default: - return($this->SetError("can not send request in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - } - if(IsSet($arguments["RequestMethod"])) - $this->request_method=$arguments["RequestMethod"]; - if(IsSet($arguments["User-Agent"])) - $this->user_agent=$arguments["User-Agent"]; - if(!IsSet($arguments["Headers"]["User-Agent"]) - && strlen($this->user_agent)) - $arguments["Headers"]["User-Agent"]=$this->user_agent; - if(IsSet($arguments["KeepAlive"])) - $this->keep_alive=intval($arguments["KeepAlive"]); - if(!IsSet($arguments["Headers"]["Connection"]) - && $this->keep_alive) - $arguments["Headers"]["Connection"]='Keep-Alive'; - if(IsSet($arguments["Accept"])) - $this->user_agent=$arguments["Accept"]; - if(!IsSet($arguments["Headers"]["Accept"]) - && strlen($this->accept)) - $arguments["Headers"]["Accept"]=$this->accept; - if(strlen($this->request_method)==0) - return($this->SetError("it was not specified a valid request method", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - if(IsSet($arguments["RequestURI"])) - $this->request_uri=$arguments["RequestURI"]; - if(strlen($this->request_uri)==0 - || substr($this->request_uri,0,1)!="/") - return($this->SetError("it was not specified a valid request URI", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $this->request_arguments=$arguments; - $this->request_headers=(IsSet($arguments["Headers"]) ? $arguments["Headers"] : array()); - $body_length=0; - $this->request_body=""; - $get_body=1; - if($this->request_method=="POST" - || $this->request_method=="PUT") - { - if(IsSet($arguments['StreamRequest'])) - { - $get_body = 0; - $this->request_headers["Transfer-Encoding"]="chunked"; - } - elseif(IsSet($arguments["PostFiles"]) - || ($this->force_multipart_form_post - && IsSet($arguments["PostValues"]))) - { - $boundary="--".md5(uniqid(time())); - $this->request_headers["Content-Type"]="multipart/form-data; boundary=".$boundary.(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : ""); - $post_parts=array(); - if(IsSet($arguments["PostValues"])) - { - $values=$arguments["PostValues"]; - if(GetType($values)!="array") - return($this->SetError("it was not specified a valid POST method values array", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - for(Reset($values),$value=0;$value$headers,"DATA"=>$data); - $body_length+=strlen($headers)+strlen($data)+strlen("\r\n"); - } - } - $body_length+=strlen("--".$boundary."--\r\n"); - $files=(IsSet($arguments["PostFiles"]) ? $arguments["PostFiles"] : array()); - Reset($files); - $end=(GetType($input=Key($files))!="string"); - for(;!$end;) - { - if(strlen($error=$this->GetFileDefinition($files[$input],$definition))) - return("3 ".$error); - $headers="--".$boundary."\r\nContent-Disposition: form-data; name=\"".$input."\"; filename=\"".$definition["NAME"]."\"\r\nContent-Type: ".$definition["Content-Type"]."\r\n\r\n"; - $part=count($post_parts); - $post_parts[$part]=array("HEADERS"=>$headers); - if(IsSet($definition["FILENAME"])) - { - $post_parts[$part]["FILENAME"]=$definition["FILENAME"]; - $data=""; - } - else - $data=$definition["DATA"]; - $post_parts[$part]["DATA"]=$data; - $body_length+=strlen($headers)+$definition["Content-Length"]+strlen("\r\n"); - Next($files); - $end=(GetType($input=Key($files))!="string"); - } - $get_body=0; - } - elseif(IsSet($arguments["PostValues"])) - { - $values=$arguments["PostValues"]; - if(GetType($values)!="array") - return($this->SetError("it was not specified a valid POST method values array", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - for(Reset($values),$value=0;$value0) - $this->request_body.="&"; - $this->request_body.=UrlEncode($k)."=".UrlEncode($values[$k][$v]); - } - } - else - { - if($value>0) - $this->request_body.="&"; - $this->request_body.=UrlEncode($k)."=".UrlEncode($values[$k]); - } - } - $this->request_headers["Content-Type"]="application/x-www-form-urlencoded".(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : ""); - $get_body=0; - } - } - if($get_body - && (IsSet($arguments["Body"]) - || IsSet($arguments["BodyStream"]))) - { - if(IsSet($arguments["Body"])) - $this->request_body=$arguments["Body"]; - else - { - $stream=$arguments["BodyStream"]; - $this->request_body=""; - for($part=0; $partrequest_body.=$stream[$part]["Data"]; - elseif(IsSet($stream[$part]["File"])) - { - if(!($file=@fopen($stream[$part]["File"],"rb"))) - return($this->SetPHPError("could not open upload file ".$stream[$part]["File"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE)); - while(!feof($file)) - { - if(GetType($block=@fread($file,$this->file_buffer_length))!="string") - { - $error=$this->SetPHPError("could not read body stream file ".$stream[$part]["File"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - fclose($file); - return($error); - } - $this->request_body.=$block; - } - fclose($file); - } - else - return("5 it was not specified a valid file or data body stream element at position ".$part); - } - } - if(!IsSet($this->request_headers["Content-Type"])) - $this->request_headers["Content-Type"]="application/octet-stream".(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : ""); - } - if(IsSet($arguments["AuthUser"])) - $this->request_user=$arguments["AuthUser"]; - elseif(IsSet($this->user)) - $this->request_user=$this->user; - if(IsSet($arguments["AuthPassword"])) - $this->request_password=$arguments["AuthPassword"]; - elseif(IsSet($this->password)) - $this->request_password=$this->password; - if(IsSet($arguments["AuthRealm"])) - $this->request_realm=$arguments["AuthRealm"]; - elseif(IsSet($this->realm)) - $this->request_realm=$this->realm; - if(IsSet($arguments["AuthWorkstation"])) - $this->request_workstation=$arguments["AuthWorkstation"]; - elseif(IsSet($this->workstation)) - $this->request_workstation=$this->workstation; - if(strlen($this->proxy_host_name)==0 - || $connect) - $request_uri=$this->request_uri; - else - { - switch(strtolower($this->protocol)) - { - case "http": - $default_port=80; - break; - case "https": - $default_port=443; - break; - } - $request_uri=strtolower($this->protocol)."://".$this->host_name.(($this->host_port==0 || $this->host_port==$default_port) ? "" : ":".$this->host_port).$this->request_uri; - } - if($this->use_curl) - { - $version=(GetType($v=curl_version())=="array" ? (IsSet($v["version"]) ? $v["version"] : "0.0.0") : (preg_match("/^libcurl\\/([0-9]+\\.[0-9]+\\.[0-9]+)/",$v,$m) ? $m[1] : "0.0.0")); - $curl_version=100000*intval($this->Tokenize($version,"."))+1000*intval($this->Tokenize("."))+intval($this->Tokenize("")); - $protocol_version=($curl_version<713002 ? "1.0" : $this->protocol_version); - } - else - $protocol_version=$this->protocol_version; - $this->request=$this->request_method." ".$request_uri." HTTP/".$protocol_version; - if($body_length - || ($body_length=strlen($this->request_body)) - || !strcmp($this->request_method, 'POST')) - $this->request_headers["Content-Length"]=$body_length; - for($headers=array(),$host_set=0,Reset($this->request_headers),$header=0;$headerrequest_headers);Next($this->request_headers),$header++) - { - $header_name=Key($this->request_headers); - $header_value=$this->request_headers[$header_name]; - if(GetType($header_value)=="array") - { - for(Reset($header_value),$value=0;$valuerequest_headers))=="host") - { - $this->request_host=strtolower($header_value); - $host_set=1; - } - } - if(!$host_set) - { - $headers[]="Host: ".$this->host_name; - $this->request_host=strtolower($this->host_name); - } - if(count($this->cookies)) - { - $cookies=array(); - $this->PickCookies($cookies,0); - if(strtolower($this->protocol)=="https") - $this->PickCookies($cookies,1); - if(count($cookies)) - { - $h=count($headers); - $headers[$h]="Cookie:"; - for(Reset($cookies),$cookie=0;$cookieuse_curl) - { - if(IsSet($arguments['StreamRequest'])) - return($this->SetError("Streaming request data is not supported when using Curl", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - if($body_length - && strlen($this->request_body)==0) - { - for($request_body="",$success=1,$part=0;$partSetPHPError("could not open upload file ".$post_parts[$part]["FILENAME"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - $success=0; - break; - } - while(!feof($file)) - { - if(GetType($block=@fread($file,$this->file_buffer_length))!="string") - { - $this->SetPHPError("could not read upload file", $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - $success=0; - break; - } - $request_body.=$block; - } - fclose($file); - if(!$success) - break; - } - $request_body.="\r\n"; - } - $request_body.="--".$boundary."--\r\n"; - } - else - $request_body=$this->request_body; - curl_setopt($this->connection,CURLOPT_HEADER,1); - curl_setopt($this->connection,CURLOPT_RETURNTRANSFER,1); - if($this->timeout) - curl_setopt($this->connection,CURLOPT_TIMEOUT,$this->timeout); - curl_setopt($this->connection,CURLOPT_SSL_VERIFYPEER,0); - curl_setopt($this->connection,CURLOPT_SSL_VERIFYHOST,0); - $request=$this->request."\r\n".implode("\r\n",$headers)."\r\n\r\n".$request_body; - curl_setopt($this->connection,CURLOPT_CUSTOMREQUEST,$request); - if($this->debug) - $this->OutputDebug("C ".$request); - if(!($success=(strlen($this->response=curl_exec($this->connection))!=0))) - { - $error=curl_error($this->connection); - $this->SetError("Could not execute the request".(strlen($error) ? ": ".$error : ""), HTTP_CLIENT_ERROR_PROTOCOL_FAILURE); - } - } - else - { - if(($success=$this->PutLine($this->request))) - { - for($header=0;$headerPutLine($headers[$header])) - break; - } - if($success - && ($success=$this->PutLine(""))) - { - if(IsSet($arguments['StreamRequest'])) - $next_state = "SendingRequestBody"; - elseif($body_length) - { - if(strlen($this->request_body)) - $success=$this->PutData($this->request_body); - else - { - for($part=0;$partPutData($post_parts[$part]["HEADERS"])) - || !($success=$this->PutData($post_parts[$part]["DATA"]))) - break; - if(IsSet($post_parts[$part]["FILENAME"])) - { - if(!($file=@fopen($post_parts[$part]["FILENAME"],"rb"))) - { - $this->SetPHPError("could not open upload file ".$post_parts[$part]["FILENAME"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - $success=0; - break; - } - while(!feof($file)) - { - if(GetType($block=@fread($file,$this->file_buffer_length))!="string") - { - $this->SetPHPError("could not read upload file", $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - $success=0; - break; - } - if(!($success=$this->PutData($block))) - break; - } - fclose($file); - if(!$success) - break; - } - if(!($success=$this->PutLine(""))) - break; - } - if($success) - $success=$this->PutLine("--".$boundary."--"); - } - if($success) - $sucess=$this->FlushData(); - } - } - } - } - if(!$success) - return($this->SetError("could not send the HTTP request: ".$this->error, $this->error_code)); - $this->state=$next_state; - return(""); - } + Function SendRequest($arguments) + { + if(strlen($this->error)) + return($this->error); + if(IsSet($arguments["ProxyUser"])) + $this->proxy_request_user=$arguments["ProxyUser"]; + elseif(IsSet($this->proxy_user)) + $this->proxy_request_user=$this->proxy_user; + if(IsSet($arguments["ProxyPassword"])) + $this->proxy_request_password=$arguments["ProxyPassword"]; + elseif(IsSet($this->proxy_password)) + $this->proxy_request_password=$this->proxy_password; + if(IsSet($arguments["ProxyRealm"])) + $this->proxy_request_realm=$arguments["ProxyRealm"]; + elseif(IsSet($this->proxy_realm)) + $this->proxy_request_realm=$this->proxy_realm; + if(IsSet($arguments["ProxyWorkstation"])) + $this->proxy_request_workstation=$arguments["ProxyWorkstation"]; + elseif(IsSet($this->proxy_workstation)) + $this->proxy_request_workstation=$this->proxy_workstation; + switch($this->state) + { + case "Disconnected": + return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "Connected": + $connect = 0; + break; + case "ConnectedToProxy": + if(strlen($error = $this->ConnectFromProxy($arguments, $headers))) + return($error); + $connect = 1; + break; + default: + return($this->SetError("can not send request in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + } + if(IsSet($arguments["RequestMethod"])) + $this->request_method=$arguments["RequestMethod"]; + if(IsSet($arguments["User-Agent"])) + $this->user_agent=$arguments["User-Agent"]; + if(!IsSet($arguments["Headers"]["User-Agent"]) + && strlen($this->user_agent)) + $arguments["Headers"]["User-Agent"]=$this->user_agent; + if(IsSet($arguments["KeepAlive"])) + $this->keep_alive=intval($arguments["KeepAlive"]); + if(!IsSet($arguments["Headers"]["Connection"]) + && $this->keep_alive) + $arguments["Headers"]["Connection"]='Keep-Alive'; + if(IsSet($arguments["Accept"])) + $this->user_agent=$arguments["Accept"]; + if(!IsSet($arguments["Headers"]["Accept"]) + && strlen($this->accept)) + $arguments["Headers"]["Accept"]=$this->accept; + if(strlen($this->request_method)==0) + return($this->SetError("it was not specified a valid request method", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + if(IsSet($arguments["RequestURI"])) + $this->request_uri=$arguments["RequestURI"]; + if(strlen($this->request_uri)==0 + || substr($this->request_uri,0,1)!="/") + return($this->SetError("it was not specified a valid request URI", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $this->request_arguments=$arguments; + $this->request_headers=(IsSet($arguments["Headers"]) ? $arguments["Headers"] : array()); + $body_length=0; + $this->request_body=""; + $get_body=1; + if($this->request_method=="POST" + || $this->request_method=="PUT") + { + if(IsSet($arguments['StreamRequest'])) + { + $get_body = 0; + $this->request_headers["Transfer-Encoding"]="chunked"; + } + elseif(IsSet($arguments["PostFiles"]) + || ($this->force_multipart_form_post + && IsSet($arguments["PostValues"]))) + { + $boundary="--".md5(uniqid(time())); + $this->request_headers["Content-Type"]="multipart/form-data; boundary=".$boundary.(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : ""); + $post_parts=array(); + if(IsSet($arguments["PostValues"])) + { + $values=$arguments["PostValues"]; + if(GetType($values)!="array") + return($this->SetError("it was not specified a valid POST method values array", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + for(Reset($values),$value=0;$value$headers,"DATA"=>$data); + $body_length+=strlen($headers)+strlen($data)+strlen("\r\n"); + } + } + $body_length+=strlen("--".$boundary."--\r\n"); + $files=(IsSet($arguments["PostFiles"]) ? $arguments["PostFiles"] : array()); + Reset($files); + $end=(GetType($input=Key($files))!="string"); + for(;!$end;) + { + if(strlen($error=$this->GetFileDefinition($files[$input],$definition))) + return("3 ".$error); + $headers="--".$boundary."\r\nContent-Disposition: form-data; name=\"".$input."\"; filename=\"".$definition["NAME"]."\"\r\nContent-Type: ".$definition["Content-Type"]."\r\n\r\n"; + $part=count($post_parts); + $post_parts[$part]=array("HEADERS"=>$headers); + if(IsSet($definition["FILENAME"])) + { + $post_parts[$part]["FILENAME"]=$definition["FILENAME"]; + $data=""; + } + else + $data=$definition["DATA"]; + $post_parts[$part]["DATA"]=$data; + $body_length+=strlen($headers)+$definition["Content-Length"]+strlen("\r\n"); + Next($files); + $end=(GetType($input=Key($files))!="string"); + } + $get_body=0; + } + elseif(IsSet($arguments["PostValues"])) + { + $values=$arguments["PostValues"]; + if(GetType($values)!="array") + return($this->SetError("it was not specified a valid POST method values array", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + for(Reset($values),$value=0;$value0) + $this->request_body.="&"; + $this->request_body.=UrlEncode($k)."=".UrlEncode($values[$k][$v]); + } + } + else + { + if($value>0) + $this->request_body.="&"; + $this->request_body.=UrlEncode($k)."=".UrlEncode($values[$k]); + } + } + $this->request_headers["Content-Type"]="application/x-www-form-urlencoded".(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : ""); + $get_body=0; + } + } + if($get_body + && (IsSet($arguments["Body"]) + || IsSet($arguments["BodyStream"]))) + { + if(IsSet($arguments["Body"])) + $this->request_body=$arguments["Body"]; + else + { + $stream=$arguments["BodyStream"]; + $this->request_body=""; + for($part=0; $partrequest_body.=$stream[$part]["Data"]; + elseif(IsSet($stream[$part]["File"])) + { + if(!($file=@fopen($stream[$part]["File"],"rb"))) + return($this->SetPHPError("could not open upload file ".$stream[$part]["File"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE)); + while(!feof($file)) + { + if(GetType($block=@fread($file,$this->file_buffer_length))!="string") + { + $error=$this->SetPHPError("could not read body stream file ".$stream[$part]["File"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + fclose($file); + return($error); + } + $this->request_body.=$block; + } + fclose($file); + } + else + return("5 it was not specified a valid file or data body stream element at position ".$part); + } + } + if(!IsSet($this->request_headers["Content-Type"])) + $this->request_headers["Content-Type"]="application/octet-stream".(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : ""); + } + if(IsSet($arguments["AuthUser"])) + $this->request_user=$arguments["AuthUser"]; + elseif(IsSet($this->user)) + $this->request_user=$this->user; + if(IsSet($arguments["AuthPassword"])) + $this->request_password=$arguments["AuthPassword"]; + elseif(IsSet($this->password)) + $this->request_password=$this->password; + if(IsSet($arguments["AuthRealm"])) + $this->request_realm=$arguments["AuthRealm"]; + elseif(IsSet($this->realm)) + $this->request_realm=$this->realm; + if(IsSet($arguments["AuthWorkstation"])) + $this->request_workstation=$arguments["AuthWorkstation"]; + elseif(IsSet($this->workstation)) + $this->request_workstation=$this->workstation; + if(strlen($this->proxy_host_name)==0 + || $connect) + $request_uri=$this->request_uri; + else + { + switch(strtolower($this->protocol)) + { + case "http": + $default_port=80; + break; + case "https": + $default_port=443; + break; + } + $request_uri=strtolower($this->protocol)."://".$this->host_name.(($this->host_port==0 || $this->host_port==$default_port) ? "" : ":".$this->host_port).$this->request_uri; + } + if($this->use_curl) + { + $version=(GetType($v=curl_version())=="array" ? (IsSet($v["version"]) ? $v["version"] : "0.0.0") : (preg_match("/^libcurl\\/([0-9]+\\.[0-9]+\\.[0-9]+)/",$v,$m) ? $m[1] : "0.0.0")); + $curl_version=100000*intval($this->Tokenize($version,"."))+1000*intval($this->Tokenize("."))+intval($this->Tokenize("")); + $protocol_version=($curl_version<713002 ? "1.0" : $this->protocol_version); + } + else + $protocol_version=$this->protocol_version; + $this->request=$this->request_method." ".$request_uri." HTTP/".$protocol_version; + if($body_length + || ($body_length=strlen($this->request_body)) + || !strcmp($this->request_method, 'POST')) + $this->request_headers["Content-Length"]=$body_length; + for($headers=array(),$host_set=0,Reset($this->request_headers),$header=0;$headerrequest_headers);Next($this->request_headers),$header++) + { + $header_name=Key($this->request_headers); + $header_value=$this->request_headers[$header_name]; + if(GetType($header_value)=="array") + { + for(Reset($header_value),$value=0;$valuerequest_headers))=="host") + { + $this->request_host=strtolower($header_value); + $host_set=1; + } + } + if(!$host_set) + { + $headers[]="Host: ".$this->host_name; + $this->request_host=strtolower($this->host_name); + } + if(count($this->cookies)) + { + $cookies=array(); + $this->PickCookies($cookies,0); + if(strtolower($this->protocol)=="https") + $this->PickCookies($cookies,1); + if(count($cookies)) + { + $h=count($headers); + $headers[$h]="Cookie:"; + for(Reset($cookies),$cookie=0;$cookieuse_curl) + { + if(IsSet($arguments['StreamRequest'])) + return($this->SetError("Streaming request data is not supported when using Curl", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + if($body_length + && strlen($this->request_body)==0) + { + for($request_body="",$success=1,$part=0;$partSetPHPError("could not open upload file ".$post_parts[$part]["FILENAME"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + $success=0; + break; + } + while(!feof($file)) + { + if(GetType($block=@fread($file,$this->file_buffer_length))!="string") + { + $this->SetPHPError("could not read upload file", $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + $success=0; + break; + } + $request_body.=$block; + } + fclose($file); + if(!$success) + break; + } + $request_body.="\r\n"; + } + $request_body.="--".$boundary."--\r\n"; + } + else + $request_body=$this->request_body; + curl_setopt($this->connection,CURLOPT_HEADER,1); + curl_setopt($this->connection,CURLOPT_RETURNTRANSFER,1); + if($this->timeout) + curl_setopt($this->connection,CURLOPT_TIMEOUT,$this->timeout); + curl_setopt($this->connection,CURLOPT_SSL_VERIFYPEER,0); + curl_setopt($this->connection,CURLOPT_SSL_VERIFYHOST,0); + $request=$this->request."\r\n".implode("\r\n",$headers)."\r\n\r\n".$request_body; + curl_setopt($this->connection,CURLOPT_CUSTOMREQUEST,$request); + if($this->debug) + $this->OutputDebug("C ".$request); + if(!($success=(strlen($this->response=curl_exec($this->connection))!=0))) + { + $error=curl_error($this->connection); + $this->SetError("Could not execute the request".(strlen($error) ? ": ".$error : ""), HTTP_CLIENT_ERROR_PROTOCOL_FAILURE); + } + } + else + { + if(($success=$this->PutLine($this->request))) + { + for($header=0;$headerPutLine($headers[$header])) + break; + } + if($success + && ($success=$this->PutLine(""))) + { + if(IsSet($arguments['StreamRequest'])) + $next_state = "SendingRequestBody"; + elseif($body_length) + { + if(strlen($this->request_body)) + $success=$this->PutData($this->request_body); + else + { + for($part=0;$partPutData($post_parts[$part]["HEADERS"])) + || !($success=$this->PutData($post_parts[$part]["DATA"]))) + break; + if(IsSet($post_parts[$part]["FILENAME"])) + { + if(!($file=@fopen($post_parts[$part]["FILENAME"],"rb"))) + { + $this->SetPHPError("could not open upload file ".$post_parts[$part]["FILENAME"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + $success=0; + break; + } + while(!feof($file)) + { + if(GetType($block=@fread($file,$this->file_buffer_length))!="string") + { + $this->SetPHPError("could not read upload file", $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + $success=0; + break; + } + if(!($success=$this->PutData($block))) + break; + } + fclose($file); + if(!$success) + break; + } + if(!($success=$this->PutLine(""))) + break; + } + if($success) + $success=$this->PutLine("--".$boundary."--"); + } + if($success) + $sucess=$this->FlushData(); + } + } + } + } + if(!$success) + return($this->SetError("could not send the HTTP request: ".$this->error, $this->error_code)); + $this->state=$next_state; + return(""); + } - Function SetCookie($name, $value, $expires="" , $path="/" , $domain="" , $secure=0, $verbatim=0) - { - if(strlen($this->error)) - return($this->error); - if(strlen($name)==0) - return($this->SetError("it was not specified a valid cookie name", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - if(strlen($path)==0 - || strcmp($path[0],"/")) - return($this->SetError($path." is not a valid path for setting cookie ".$name, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - if($domain=="" - || !strpos($domain,".",$domain[0]=="." ? 1 : 0)) - return($this->SetError($domain." is not a valid domain for setting cookie ".$name, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $domain=strtolower($domain); - if(!strcmp($domain[0],".")) - $domain=substr($domain,1); - if(!$verbatim) - { - $name=$this->CookieEncode($name,1); - $value=$this->CookieEncode($value,0); - } - $secure=intval($secure); - $this->cookies[$secure][$domain][$path][$name]=array( - "name"=>$name, - "value"=>$value, - "domain"=>$domain, - "path"=>$path, - "expires"=>$expires, - "secure"=>$secure - ); - return(""); - } + Function SetCookie($name, $value, $expires="" , $path="/" , $domain="" , $secure=0, $verbatim=0) + { + if(strlen($this->error)) + return($this->error); + if(strlen($name)==0) + return($this->SetError("it was not specified a valid cookie name", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + if(strlen($path)==0 + || strcmp($path[0],"/")) + return($this->SetError($path." is not a valid path for setting cookie ".$name, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + if($domain=="" + || !strpos($domain,".",$domain[0]=="." ? 1 : 0)) + return($this->SetError($domain." is not a valid domain for setting cookie ".$name, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $domain=strtolower($domain); + if(!strcmp($domain[0],".")) + $domain=substr($domain,1); + if(!$verbatim) + { + $name=$this->CookieEncode($name,1); + $value=$this->CookieEncode($value,0); + } + $secure=intval($secure); + $this->cookies[$secure][$domain][$path][$name]=array( + "name"=>$name, + "value"=>$value, + "domain"=>$domain, + "path"=>$path, + "expires"=>$expires, + "secure"=>$secure + ); + return(""); + } - Function SendRequestBody($data, $end_of_data) - { - if(strlen($this->error)) - return($this->error); - switch($this->state) - { - case "Disconnected": - return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "Connected": - case "ConnectedToProxy": - return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "SendingRequestBody": - break; - case "RequestSent": - return($this->SetError("request body was already sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - default: - return($this->SetError("can not send the request body in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - } - $length = strlen($data); - if($length) - { - $size = dechex($length)."\r\n"; - if(!$this->PutData($size) - || !$this->PutData($data)) - return($this->error); - } - if($end_of_data) - { - $size = "0\r\n"; - if(!$this->PutData($size)) - return($this->error); - $this->state = "RequestSent"; - } - return(""); - } + Function SendRequestBody($data, $end_of_data) + { + if(strlen($this->error)) + return($this->error); + switch($this->state) + { + case "Disconnected": + return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "Connected": + case "ConnectedToProxy": + return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "SendingRequestBody": + break; + case "RequestSent": + return($this->SetError("request body was already sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + default: + return($this->SetError("can not send the request body in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + } + $length = strlen($data); + if($length) + { + $size = dechex($length)."\r\n"; + if(!$this->PutData($size) + || !$this->PutData($data)) + return($this->error); + } + if($end_of_data) + { + $size = "0\r\n"; + if(!$this->PutData($size)) + return($this->error); + $this->state = "RequestSent"; + } + return(""); + } - Function ReadReplyHeadersResponse(&$headers) - { - $headers=array(); - if(strlen($this->error)) - return($this->error); - switch($this->state) - { - case "Disconnected": - return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "Connected": - return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "ConnectedToProxy": - return($this->SetError("connection from the remote server from the proxy was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "SendingRequestBody": - return($this->SetError("request body data was not completely sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "ConnectSent": - $connect = 1; - break; - case "RequestSent": - $connect = 0; - break; - default: - return($this->SetError("can not get request headers in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - } - $this->content_length=$this->read_length=$this->read_response=$this->remaining_chunk=0; - $this->content_length_set=$this->chunked=$this->last_chunk_read=$chunked=0; - $this->force_close = $this->connection_close=0; - for($this->response_status="";;) - { - $line=$this->GetLine(); - if(GetType($line)!="string") - return($this->SetError("could not read request reply: ".$this->error, $this->error_code)); - if(strlen($this->response_status)==0) - { - if(!preg_match($match="/^http\\/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$/i",$line,$matches)) - return($this->SetError("it was received an unexpected HTTP response status", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - $this->response_status=$matches[1]; - $this->response_message=$matches[2]; - if($this->response_status == 204) - { - $this->content_length = 0; - $this->content_length_set = 1; - } - } - if($line=="") - { - if(strlen($this->response_status)==0) - return($this->SetError("it was not received HTTP response status", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - $this->state=($connect ? "GotConnectHeaders" : "GotReplyHeaders"); - break; - } - $header_name=strtolower($this->Tokenize($line,":")); - $header_value=Trim(Chop($this->Tokenize("\r\n"))); - if(IsSet($headers[$header_name])) - { - if(GetType($headers[$header_name])=="string") - $headers[$header_name]=array($headers[$header_name]); - $headers[$header_name][]=$header_value; - } - else - $headers[$header_name]=$header_value; - if(!$connect) - { - switch($header_name) - { - case "content-length": - $this->content_length=intval($headers[$header_name]); - $this->content_length_set=1; - break; - case "transfer-encoding": - $encoding=$this->Tokenize($header_value,"; \t"); - if(!$this->use_curl - && !strcmp($encoding,"chunked")) - $chunked=1; - break; - case "set-cookie": - if($this->support_cookies) - { - if(GetType($headers[$header_name])=="array") - $cookie_headers=$headers[$header_name]; - else - $cookie_headers=array($headers[$header_name]); - for($cookie=0;$cookieTokenize($cookie_headers[$cookie],"=")); - $cookie_value=$this->Tokenize(";"); - $domain=$this->request_host; - $path="/"; - $expires=""; - $secure=0; - while(($name = strtolower(trim(UrlDecode($this->Tokenize("=")))))!="") - { - $value=UrlDecode($this->Tokenize(";")); - switch($name) - { - case "domain": - $domain=$value; - break; - case "path": - $path=$value; - break; - case "expires": - if(preg_match("/^((Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday|Sun|Sunday), )?([0-9]{2})\\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\-([0-9]{2,4}) ([0-9]{2})\\:([0-9]{2})\\:([0-9]{2}) GMT\$/",$value,$matches)) - { - $year=intval($matches[5]); - if($year<1900) - $year+=($year<70 ? 2000 : 1900); - $expires="$year-".$this->months[$matches[4]]."-".$matches[3]." ".$matches[6].":".$matches[7].":".$matches[8]; - } - break; - case "secure": - $secure=1; - break; - } - } - if(strlen($this->SetCookie($cookie_name, $cookie_value, $expires, $path , $domain, $secure, 1))) - $this->error=""; - } - } - break; - case "connection": - $this->force_close = $this->connection_close=!strcmp(strtolower($header_value),"close"); - break; - } - } - } - $this->chunked=$chunked; - if($this->content_length_set) - $this->connection_close=0; - return(""); - } + Function ReadReplyHeadersResponse(&$headers) + { + $headers=array(); + if(strlen($this->error)) + return($this->error); + switch($this->state) + { + case "Disconnected": + return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "Connected": + return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "ConnectedToProxy": + return($this->SetError("connection from the remote server from the proxy was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "SendingRequestBody": + return($this->SetError("request body data was not completely sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "ConnectSent": + $connect = 1; + break; + case "RequestSent": + $connect = 0; + break; + default: + return($this->SetError("can not get request headers in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + } + $this->content_length=$this->read_length=$this->read_response=$this->remaining_chunk=0; + $this->content_length_set=$this->chunked=$this->last_chunk_read=$chunked=0; + $this->force_close = $this->connection_close=0; + for($this->response_status="";;) + { + $line=$this->GetLine(); + if(GetType($line)!="string") + return($this->SetError("could not read request reply: ".$this->error, $this->error_code)); + if(strlen($this->response_status)==0) + { + if(!preg_match($match="/^http\\/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$/i",$line,$matches)) + return($this->SetError("it was received an unexpected HTTP response status", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + $this->response_status=$matches[1]; + $this->response_message=$matches[2]; + if($this->response_status == 204) + { + $this->content_length = 0; + $this->content_length_set = 1; + } + } + if($line=="") + { + if(strlen($this->response_status)==0) + return($this->SetError("it was not received HTTP response status", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + $this->state=($connect ? "GotConnectHeaders" : "GotReplyHeaders"); + break; + } + $header_name=strtolower($this->Tokenize($line,":")); + $header_value=Trim(Chop($this->Tokenize("\r\n"))); + if(IsSet($headers[$header_name])) + { + if(GetType($headers[$header_name])=="string") + $headers[$header_name]=array($headers[$header_name]); + $headers[$header_name][]=$header_value; + } + else + $headers[$header_name]=$header_value; + if(!$connect) + { + switch($header_name) + { + case "content-length": + $this->content_length=intval($headers[$header_name]); + $this->content_length_set=1; + break; + case "transfer-encoding": + $encoding=$this->Tokenize($header_value,"; \t"); + if(!$this->use_curl + && !strcmp($encoding,"chunked")) + $chunked=1; + break; + case "set-cookie": + if($this->support_cookies) + { + if(GetType($headers[$header_name])=="array") + $cookie_headers=$headers[$header_name]; + else + $cookie_headers=array($headers[$header_name]); + for($cookie=0;$cookieTokenize($cookie_headers[$cookie],"=")); + $cookie_value=$this->Tokenize(";"); + $domain=$this->request_host; + $path="/"; + $expires=""; + $secure=0; + while(($name = strtolower(trim(UrlDecode($this->Tokenize("=")))))!="") + { + $value=UrlDecode($this->Tokenize(";")); + switch($name) + { + case "domain": + $domain=$value; + break; + case "path": + $path=$value; + break; + case "expires": + if(preg_match("/^((Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday|Sun|Sunday), )?([0-9]{2})\\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\-([0-9]{2,4}) ([0-9]{2})\\:([0-9]{2})\\:([0-9]{2}) GMT\$/",$value,$matches)) + { + $year=intval($matches[5]); + if($year<1900) + $year+=($year<70 ? 2000 : 1900); + $expires="$year-".$this->months[$matches[4]]."-".$matches[3]." ".$matches[6].":".$matches[7].":".$matches[8]; + } + break; + case "secure": + $secure=1; + break; + } + } + if(strlen($this->SetCookie($cookie_name, $cookie_value, $expires, $path , $domain, $secure, 1))) + $this->error=""; + } + } + break; + case "connection": + $this->force_close = $this->connection_close=!strcmp(strtolower($header_value),"close"); + break; + } + } + } + $this->chunked=$chunked; + if($this->content_length_set) + $this->connection_close=0; + return(""); + } - Function Redirect(&$headers) - { - if($this->follow_redirect) - { - if(!IsSet($headers["location"]) - || (GetType($headers["location"])!="array" - && strlen($location=$headers["location"])==0) - || (GetType($headers["location"])=="array" - && strlen($location=$headers["location"][0])==0)) - return($this->SetError("it was received a redirect without location URL", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - if(strcmp($location[0],"/")) - { - if(!($location_arguments=@parse_url($location))) - return($this->SetError("the server did not return a valid redirection location URL", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - if(!IsSet($location_arguments["scheme"])) - $location=((GetType($end=strrpos($this->request_uri,"/"))=="integer" && $end>1) ? substr($this->request_uri,0,$end) : "")."/".$location; - } - if(!strcmp($location[0],"/")) - $location=$this->protocol."://".$this->host_name.($this->host_port ? ":".$this->host_port : "").$location; - $error=$this->GetRequestArguments($location,$arguments); - if(strlen($error)) - return($this->SetError("could not process redirect url: ".$error, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - $arguments["RequestMethod"]="GET"; - if(strlen($error=$this->Close())==0 - && strlen($error=$this->Open($arguments))==0 - && strlen($error=$this->SendRequest($arguments))==0) - { - $this->redirection_level++; - if($this->redirection_level>$this->redirection_limit) - { - $error="it was exceeded the limit of request redirections"; - $this->error_code = HTTP_CLIENT_ERROR_PROTOCOL_FAILURE; - } - else - $error=$this->ReadReplyHeaders($headers); - $this->redirection_level--; - } - if(strlen($error)) - return($this->SetError($error, $this->error_code)); - } - return(""); - } + Function Redirect(&$headers) + { + if($this->follow_redirect) + { + if(!IsSet($headers["location"]) + || (GetType($headers["location"])!="array" + && strlen($location=$headers["location"])==0) + || (GetType($headers["location"])=="array" + && strlen($location=$headers["location"][0])==0)) + return($this->SetError("it was received a redirect without location URL", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + if(strcmp($location[0],"/")) + { + if(!($location_arguments=@parse_url($location))) + return($this->SetError("the server did not return a valid redirection location URL", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + if(!IsSet($location_arguments["scheme"])) + $location=((GetType($end=strrpos($this->request_uri,"/"))=="integer" && $end>1) ? substr($this->request_uri,0,$end) : "")."/".$location; + } + if(!strcmp($location[0],"/")) + $location=$this->protocol."://".$this->host_name.($this->host_port ? ":".$this->host_port : "").$location; + $error=$this->GetRequestArguments($location,$arguments); + if(strlen($error)) + return($this->SetError("could not process redirect url: ".$error, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + $arguments["RequestMethod"]="GET"; + if(strlen($error=$this->Close())==0 + && strlen($error=$this->Open($arguments))==0 + && strlen($error=$this->SendRequest($arguments))==0) + { + $this->redirection_level++; + if($this->redirection_level>$this->redirection_limit) + { + $error="it was exceeded the limit of request redirections"; + $this->error_code = HTTP_CLIENT_ERROR_PROTOCOL_FAILURE; + } + else + $error=$this->ReadReplyHeaders($headers); + $this->redirection_level--; + } + if(strlen($error)) + return($this->SetError($error, $this->error_code)); + } + return(""); + } - Function Authenticate(&$headers, $proxy, &$proxy_authorization, &$user, &$password, &$realm, &$workstation) - { - if($proxy) - { - $authenticate_header="proxy-authenticate"; - $authorization_header="Proxy-Authorization"; - $authenticate_status="407"; - $authentication_mechanism=$this->proxy_authentication_mechanism; - } - else - { - $authenticate_header="www-authenticate"; - $authorization_header="Authorization"; - $authenticate_status="401"; - $authentication_mechanism=$this->authentication_mechanism; - } - if(IsSet($headers[$authenticate_header]) - && $this->sasl_authenticate) - { - if(function_exists("class_exists") - && !class_exists("sasl_client_class")) - return($this->SetError("the SASL client class needs to be loaded to be able to authenticate".($proxy ? " with the proxy server" : "")." and access this site", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - if(GetType($headers[$authenticate_header])=="array") - $authenticate=$headers[$authenticate_header]; - else - $authenticate=array($headers[$authenticate_header]); - for($response="", $mechanisms=array(),$m=0;$mTokenize($authenticate[$m]," "); - $response=$this->Tokenize(""); - if(strlen($authentication_mechanism)) - { - if(!strcmp($authentication_mechanism,$mechanism)) - { - $mechanisms[]=$mechanism; - break; - } - } - else - $mechanisms[]=$mechanism; - } - $sasl=new sasl_client_class; - if(IsSet($user)) - $sasl->SetCredential("user",$user); - if(IsSet($password)) - $sasl->SetCredential("password",$password); - if(IsSet($realm)) - $sasl->SetCredential("realm",$realm); - if(IsSet($workstation)) - $sasl->SetCredential("workstation",$workstation); - $sasl->SetCredential("uri",$this->request_uri); - $sasl->SetCredential("method",$this->request_method); - $sasl->SetCredential("session",$this->session); - do - { - $status=$sasl->Start($mechanisms,$message,$interactions); - } - while($status==SASL_INTERACT); - switch($status) - { - case SASL_CONTINUE: - break; - case SASL_NOMECH: - return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".(strlen($authentication_mechanism) ? "authentication mechanism ".$authentication_mechanism." may not be used: " : "").$sasl->error, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - default: - return($this->SetError("Could not start the SASL ".($proxy ? "proxy " : "")."authentication client: ".$sasl->error, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - } - if($proxy >= 0) - { - for(;;) - { - if(strlen($error=$this->ReadReplyBody($body,$this->file_buffer_length))) - return($error); - if(strlen($body)==0) - break; - } - } - $authorization_value=$sasl->mechanism.(IsSet($message) ? " ".($sasl->encode_response ? base64_encode($message) : $message) : ""); - $request_arguments=$this->request_arguments; - $arguments=$request_arguments; - $arguments["Headers"][$authorization_header]=$authorization_value; - if(!$proxy - && strlen($proxy_authorization)) - $arguments["Headers"]["Proxy-Authorization"]=$proxy_authorization; - if(strlen($error=$this->Close()) - || strlen($error=$this->Open($arguments))) - return($this->SetError($error, $this->error_code)); - $authenticated=0; - if(IsSet($message)) - { - if($proxy < 0) - { - if(strlen($error=$this->ConnectFromProxy($arguments, $headers))) - return($this->SetError($error, $this->error_code)); - } - else - { - if(strlen($error=$this->SendRequest($arguments)) - || strlen($error=$this->ReadReplyHeadersResponse($headers))) - return($this->SetError($error, $this->error_code)); - } - if(!IsSet($headers[$authenticate_header])) - $authenticate=array(); - elseif(GetType($headers[$authenticate_header])=="array") - $authenticate=$headers[$authenticate_header]; - else - $authenticate=array($headers[$authenticate_header]); - for($mechanism=0;$mechanismTokenize($authenticate[$mechanism]," "),$sasl->mechanism)) - { - $response=$this->Tokenize(""); - break; - } - } - switch($this->response_status) - { - case $authenticate_status: - break; - case "301": - case "302": - case "303": - case "307": - if($proxy >= 0) - return($this->Redirect($headers)); - default: - if(intval($this->response_status/100)==2) - { - if($proxy) - $proxy_authorization=$authorization_value; - $authenticated=1; - break; - } - if($proxy - && !strcmp($this->response_status,"401")) - { - $proxy_authorization=$authorization_value; - $authenticated=1; - break; - } - return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".$this->response_status." ".$this->response_message, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - } - } - for(;!$authenticated;) - { - do - { - $status=$sasl->Step($response,$message,$interactions); - } - while($status==SASL_INTERACT); - switch($status) - { - case SASL_CONTINUE: - $authorization_value=$sasl->mechanism.(IsSet($message) ? " ".($sasl->encode_response ? base64_encode($message) : $message) : ""); - $arguments=$request_arguments; - $arguments["Headers"][$authorization_header]=$authorization_value; - if(!$proxy - && strlen($proxy_authorization)) - $arguments["Headers"]["Proxy-Authorization"]=$proxy_authorization; - if($proxy < 0) - { - if(strlen($error=$this->ConnectFromProxy($arguments, $headers))) - return($this->SetError($error, $this->error_code)); - } - else - { - if(strlen($error=$this->SendRequest($arguments)) - || strlen($error=$this->ReadReplyHeadersResponse($headers))) - return($this->SetError($error, $this->error_code)); - } - switch($this->response_status) - { - case $authenticate_status: - if(GetType($headers[$authenticate_header])=="array") - $authenticate=$headers[$authenticate_header]; - else - $authenticate=array($headers[$authenticate_header]); - for($response="",$mechanism=0;$mechanismTokenize($authenticate[$mechanism]," "),$sasl->mechanism)) - { - $response=$this->Tokenize(""); - break; - } - } - if($proxy >= 0) - { - for(;;) - { - if(strlen($error=$this->ReadReplyBody($body,$this->file_buffer_length))) - return($error); - if(strlen($body)==0) - break; - } - } - $this->state="Connected"; - break; - case "301": - case "302": - case "303": - case "307": - if($proxy >= 0) - return($this->Redirect($headers)); - default: - if(intval($this->response_status/100)==2) - { - if($proxy) - $proxy_authorization=$authorization_value; - $authenticated=1; - break; - } - if($proxy - && !strcmp($this->response_status,"401")) - { - $proxy_authorization=$authorization_value; - $authenticated=1; - break; - } - return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".$this->response_status." ".$this->response_message)); - } - break; - default: - return($this->SetError("Could not process the SASL ".($proxy ? "proxy " : "")."authentication step: ".$sasl->error, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); - } - } - } - return(""); - } - - Function ReadReplyHeaders(&$headers) - { - if(strlen($error=$this->ReadReplyHeadersResponse($headers))) - return($error); - $proxy_authorization=""; - while(!strcmp($this->response_status, "100")) - { - $this->state="RequestSent"; - if(strlen($error=$this->ReadReplyHeadersResponse($headers))) - return($error); - } - switch($this->response_status) - { - case "301": - case "302": - case "303": - case "307": - if(strlen($error=$this->Redirect($headers))) - return($error); - break; - case "407": - if(strlen($error=$this->Authenticate($headers, 1, $proxy_authorization, $this->proxy_request_user, $this->proxy_request_password, $this->proxy_request_realm, $this->proxy_request_workstation))) - return($error); - if(strcmp($this->response_status,"401")) - return(""); - case "401": - return($this->Authenticate($headers, 0, $proxy_authorization, $this->request_user, $this->request_password, $this->request_realm, $this->request_workstation)); - } - return(""); - } + Function Authenticate(&$headers, $proxy, &$proxy_authorization, &$user, &$password, &$realm, &$workstation) + { + if($proxy) + { + $authenticate_header="proxy-authenticate"; + $authorization_header="Proxy-Authorization"; + $authenticate_status="407"; + $authentication_mechanism=$this->proxy_authentication_mechanism; + } + else + { + $authenticate_header="www-authenticate"; + $authorization_header="Authorization"; + $authenticate_status="401"; + $authentication_mechanism=$this->authentication_mechanism; + } + if(IsSet($headers[$authenticate_header]) + && $this->sasl_authenticate) + { + if(function_exists("class_exists") + && !class_exists("sasl_client_class")) + return($this->SetError("the SASL client class needs to be loaded to be able to authenticate".($proxy ? " with the proxy server" : "")." and access this site", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + if(GetType($headers[$authenticate_header])=="array") + $authenticate=$headers[$authenticate_header]; + else + $authenticate=array($headers[$authenticate_header]); + for($response="", $mechanisms=array(),$m=0;$mTokenize($authenticate[$m]," "); + $response=$this->Tokenize(""); + if(strlen($authentication_mechanism)) + { + if(!strcmp($authentication_mechanism,$mechanism)) + { + $mechanisms[]=$mechanism; + break; + } + } + else + $mechanisms[]=$mechanism; + } + $sasl=new sasl_client_class; + if(IsSet($user)) + $sasl->SetCredential("user",$user); + if(IsSet($password)) + $sasl->SetCredential("password",$password); + if(IsSet($realm)) + $sasl->SetCredential("realm",$realm); + if(IsSet($workstation)) + $sasl->SetCredential("workstation",$workstation); + $sasl->SetCredential("uri",$this->request_uri); + $sasl->SetCredential("method",$this->request_method); + $sasl->SetCredential("session",$this->session); + do + { + $status=$sasl->Start($mechanisms,$message,$interactions); + } + while($status==SASL_INTERACT); + switch($status) + { + case SASL_CONTINUE: + break; + case SASL_NOMECH: + return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".(strlen($authentication_mechanism) ? "authentication mechanism ".$authentication_mechanism." may not be used: " : "").$sasl->error, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + default: + return($this->SetError("Could not start the SASL ".($proxy ? "proxy " : "")."authentication client: ".$sasl->error, HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + } + if($proxy >= 0) + { + for(;;) + { + if(strlen($error=$this->ReadReplyBody($body,$this->file_buffer_length))) + return($error); + if(strlen($body)==0) + break; + } + } + $authorization_value=$sasl->mechanism.(IsSet($message) ? " ".($sasl->encode_response ? base64_encode($message) : $message) : ""); + $request_arguments=$this->request_arguments; + $arguments=$request_arguments; + $arguments["Headers"][$authorization_header]=$authorization_value; + if(!$proxy + && strlen($proxy_authorization)) + $arguments["Headers"]["Proxy-Authorization"]=$proxy_authorization; + if(strlen($error=$this->Close()) + || strlen($error=$this->Open($arguments))) + return($this->SetError($error, $this->error_code)); + $authenticated=0; + if(IsSet($message)) + { + if($proxy < 0) + { + if(strlen($error=$this->ConnectFromProxy($arguments, $headers))) + return($this->SetError($error, $this->error_code)); + } + else + { + if(strlen($error=$this->SendRequest($arguments)) + || strlen($error=$this->ReadReplyHeadersResponse($headers))) + return($this->SetError($error, $this->error_code)); + } + if(!IsSet($headers[$authenticate_header])) + $authenticate=array(); + elseif(GetType($headers[$authenticate_header])=="array") + $authenticate=$headers[$authenticate_header]; + else + $authenticate=array($headers[$authenticate_header]); + for($mechanism=0;$mechanismTokenize($authenticate[$mechanism]," "),$sasl->mechanism)) + { + $response=$this->Tokenize(""); + break; + } + } + switch($this->response_status) + { + case $authenticate_status: + break; + case "301": + case "302": + case "303": + case "307": + if($proxy >= 0) + return($this->Redirect($headers)); + default: + if(intval($this->response_status/100)==2) + { + if($proxy) + $proxy_authorization=$authorization_value; + $authenticated=1; + break; + } + if($proxy + && !strcmp($this->response_status,"401")) + { + $proxy_authorization=$authorization_value; + $authenticated=1; + break; + } + return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".$this->response_status." ".$this->response_message, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + } + } + for(;!$authenticated;) + { + do + { + $status=$sasl->Step($response,$message,$interactions); + } + while($status==SASL_INTERACT); + switch($status) + { + case SASL_CONTINUE: + $authorization_value=$sasl->mechanism.(IsSet($message) ? " ".($sasl->encode_response ? base64_encode($message) : $message) : ""); + $arguments=$request_arguments; + $arguments["Headers"][$authorization_header]=$authorization_value; + if(!$proxy + && strlen($proxy_authorization)) + $arguments["Headers"]["Proxy-Authorization"]=$proxy_authorization; + if($proxy < 0) + { + if(strlen($error=$this->ConnectFromProxy($arguments, $headers))) + return($this->SetError($error, $this->error_code)); + } + else + { + if(strlen($error=$this->SendRequest($arguments)) + || strlen($error=$this->ReadReplyHeadersResponse($headers))) + return($this->SetError($error, $this->error_code)); + } + switch($this->response_status) + { + case $authenticate_status: + if(GetType($headers[$authenticate_header])=="array") + $authenticate=$headers[$authenticate_header]; + else + $authenticate=array($headers[$authenticate_header]); + for($response="",$mechanism=0;$mechanismTokenize($authenticate[$mechanism]," "),$sasl->mechanism)) + { + $response=$this->Tokenize(""); + break; + } + } + if($proxy >= 0) + { + for(;;) + { + if(strlen($error=$this->ReadReplyBody($body,$this->file_buffer_length))) + return($error); + if(strlen($body)==0) + break; + } + } + $this->state="Connected"; + break; + case "301": + case "302": + case "303": + case "307": + if($proxy >= 0) + return($this->Redirect($headers)); + default: + if(intval($this->response_status/100)==2) + { + if($proxy) + $proxy_authorization=$authorization_value; + $authenticated=1; + break; + } + if($proxy + && !strcmp($this->response_status,"401")) + { + $proxy_authorization=$authorization_value; + $authenticated=1; + break; + } + return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".$this->response_status." ".$this->response_message)); + } + break; + default: + return($this->SetError("Could not process the SASL ".($proxy ? "proxy " : "")."authentication step: ".$sasl->error, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE)); + } + } + } + return(""); + } - Function ReadReplyBody(&$body,$length) - { - $body=""; - if(strlen($this->error)) - return($this->error); - switch($this->state) - { - case "Disconnected": - return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "Connected": - case "ConnectedToProxy": - return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - case "RequestSent": - if(($error=$this->ReadReplyHeaders($headers))!="") - return($error); - break; - case "GotReplyHeaders": - break; - case 'ResponseReceived': - $body = ''; - return(''); - default: - return($this->SetError("can not get request headers in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - } - if($this->content_length_set) - $length=min($this->content_length-$this->read_length,$length); - $body = ''; - if($length>0) - { - if(!$this->EndOfInput() - && ($body=$this->ReadBytes($length))=="") - { - if(strlen($this->error)) - return($this->SetError("could not get the request reply body: ".$this->error, $this->error_code)); - } - $this->read_length+=strlen($body); - if($this->EndOfInput()) - $this->state = 'ResponseReceived'; - } - return(""); - } + Function ReadReplyHeaders(&$headers) + { + if(strlen($error=$this->ReadReplyHeadersResponse($headers))) + return($error); + $proxy_authorization=""; + while(!strcmp($this->response_status, "100")) + { + $this->state="RequestSent"; + if(strlen($error=$this->ReadReplyHeadersResponse($headers))) + return($error); + } + switch($this->response_status) + { + case "301": + case "302": + case "303": + case "307": + if(strlen($error=$this->Redirect($headers))) + return($error); + break; + case "407": + if(strlen($error=$this->Authenticate($headers, 1, $proxy_authorization, $this->proxy_request_user, $this->proxy_request_password, $this->proxy_request_realm, $this->proxy_request_workstation))) + return($error); + if(strcmp($this->response_status,"401")) + return(""); + case "401": + return($this->Authenticate($headers, 0, $proxy_authorization, $this->request_user, $this->request_password, $this->request_realm, $this->request_workstation)); + } + return(""); + } - Function ReadWholeReplyBody(&$body) - { - $body = ''; - for(;;) - { - if(strlen($error = $this->ReadReplyBody($block, $this->file_buffer_length))) - return($error); - if(strlen($block) == 0) - return(''); - $body .= $block; - } - } + Function ReadReplyBody(&$body,$length) + { + $body=""; + if(strlen($this->error)) + return($this->error); + switch($this->state) + { + case "Disconnected": + return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "Connected": + case "ConnectedToProxy": + return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + case "RequestSent": + if(($error=$this->ReadReplyHeaders($headers))!="") + return($error); + break; + case "GotReplyHeaders": + break; + case 'ResponseReceived': + $body = ''; + return(''); + default: + return($this->SetError("can not get request headers in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + } + if($this->content_length_set) + $length=min($this->content_length-$this->read_length,$length); + $body = ''; + if($length>0) + { + if(!$this->EndOfInput() + && ($body=$this->ReadBytes($length))=="") + { + if(strlen($this->error)) + return($this->SetError("could not get the request reply body: ".$this->error, $this->error_code)); + } + $this->read_length+=strlen($body); + if($this->EndOfInput()) + $this->state = 'ResponseReceived'; + } + return(""); + } - Function ReadWholeReplyIntoTemporaryFile(&$file) - { - if(!($file = tmpfile())) - return $this->SetPHPError('could not create the temporary file to save the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - for(;;) - { - if(strlen($error = $this->ReadReplyBody($block, $this->file_buffer_length))) - { - fclose($file); - return($error); - } - if(strlen($block) == 0) - { - if(@fseek($file, 0) != 0) - { - $error = $this->SetPHPError('could not seek to the beginning of temporary file with the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - fclose($file); - return $error; - } - return(''); - } - if(!@fwrite($file, $block)) - { - $error = $this->SetPHPError('could not write to the temporary file to save the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); - fclose($file); - return $error; - } - } - } + Function ReadWholeReplyBody(&$body) + { + $body = ''; + for(;;) + { + if(strlen($error = $this->ReadReplyBody($block, $this->file_buffer_length))) + return($error); + if(strlen($block) == 0) + return(''); + $body .= $block; + } + } - Function SaveCookies(&$cookies, $domain='', $secure_only=0, $persistent_only=0) - { - $now=gmdate("Y-m-d H-i-s"); - $cookies=array(); - for($secure_cookies=0,Reset($this->cookies);$secure_cookiescookies);Next($this->cookies),$secure_cookies++) - { - $secure=Key($this->cookies); - if(!$secure_only - || $secure) - { - for($cookie_domain=0,Reset($this->cookies[$secure]);$cookie_domaincookies[$secure]);Next($this->cookies[$secure]),$cookie_domain++) - { - $domain_pattern=Key($this->cookies[$secure]); - $match=strlen($domain)-strlen($domain_pattern); - if(strlen($domain)==0 - || ($match>=0 - && !strcmp($domain_pattern,substr($domain,$match)) - && ($match==0 - || $domain_pattern[0]=="." - || $domain[$match-1]=="."))) - { - for(Reset($this->cookies[$secure][$domain_pattern]),$path_part=0;$path_partcookies[$secure][$domain_pattern]);Next($this->cookies[$secure][$domain_pattern]),$path_part++) - { - $path=Key($this->cookies[$secure][$domain_pattern]); - for(Reset($this->cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookiecookies[$secure][$domain_pattern][$path]);Next($this->cookies[$secure][$domain_pattern][$path]),$cookie++) - { - $cookie_name=Key($this->cookies[$secure][$domain_pattern][$path]); - $expires=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]["expires"]; - if((!$persistent_only - && strlen($expires)==0) - || (strlen($expires) - && strcmp($now,$expires)<0)) - $cookies[$secure][$domain_pattern][$path][$cookie_name]=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]; - } - } - } - } - } - } - } + Function ReadWholeReplyIntoTemporaryFile(&$file) + { + if(!($file = tmpfile())) + return $this->SetPHPError('could not create the temporary file to save the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + for(;;) + { + if(strlen($error = $this->ReadReplyBody($block, $this->file_buffer_length))) + { + fclose($file); + return($error); + } + if(strlen($block) == 0) + { + if(@fseek($file, 0) != 0) + { + $error = $this->SetPHPError('could not seek to the beginning of temporary file with the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + fclose($file); + return $error; + } + return(''); + } + if(!@fwrite($file, $block)) + { + $error = $this->SetPHPError('could not write to the temporary file to save the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE); + fclose($file); + return $error; + } + } + } - Function SavePersistentCookies(&$cookies, $domain='', $secure_only=0) - { - $this->SaveCookies($cookies, $domain, $secure_only, 1); - } + Function SaveCookies(&$cookies, $domain='', $secure_only=0, $persistent_only=0) + { + $now=gmdate("Y-m-d H-i-s"); + $cookies=array(); + for($secure_cookies=0,Reset($this->cookies);$secure_cookiescookies);Next($this->cookies),$secure_cookies++) + { + $secure=Key($this->cookies); + if(!$secure_only + || $secure) + { + for($cookie_domain=0,Reset($this->cookies[$secure]);$cookie_domaincookies[$secure]);Next($this->cookies[$secure]),$cookie_domain++) + { + $domain_pattern=Key($this->cookies[$secure]); + $match=strlen($domain)-strlen($domain_pattern); + if(strlen($domain)==0 + || ($match>=0 + && !strcmp($domain_pattern,substr($domain,$match)) + && ($match==0 + || $domain_pattern[0]=="." + || $domain[$match-1]=="."))) + { + for(Reset($this->cookies[$secure][$domain_pattern]),$path_part=0;$path_partcookies[$secure][$domain_pattern]);Next($this->cookies[$secure][$domain_pattern]),$path_part++) + { + $path=Key($this->cookies[$secure][$domain_pattern]); + for(Reset($this->cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookiecookies[$secure][$domain_pattern][$path]);Next($this->cookies[$secure][$domain_pattern][$path]),$cookie++) + { + $cookie_name=Key($this->cookies[$secure][$domain_pattern][$path]); + $expires=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]["expires"]; + if((!$persistent_only + && strlen($expires)==0) + || (strlen($expires) + && strcmp($now,$expires)<0)) + $cookies[$secure][$domain_pattern][$path][$cookie_name]=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]; + } + } + } + } + } + } + } - Function GetPersistentCookies(&$cookies, $domain='', $secure_only=0) - { - $this->SavePersistentCookies($cookies, $domain, $secure_only); - } + Function SavePersistentCookies(&$cookies, $domain='', $secure_only=0) + { + $this->SaveCookies($cookies, $domain, $secure_only, 1); + } - Function RestoreCookies($cookies, $clear=1) - { - $new_cookies=($clear ? array() : $this->cookies); - for($secure_cookies=0, Reset($cookies); $secure_cookiesSetError("invalid cookie secure value type (".serialize($secure).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - for($cookie_domain=0,Reset($cookies[$secure]);$cookie_domainSetError("invalid cookie domain value type (".serialize($domain_pattern).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - for(Reset($cookies[$secure][$domain_pattern]),$path_part=0;$path_partSetError("invalid cookie path value type (".serialize($path).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - for(Reset($cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookieSetError("invalid cookie expiry value type (".serialize($expires).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); - $new_cookies[$secure][$domain_pattern][$path][$cookie_name]=array( - "name"=>$cookie_name, - "value"=>$value, - "domain"=>$domain_pattern, - "path"=>$path, - "expires"=>$expires, - "secure"=>$secure - ); - } - } - } - } - $this->cookies=$new_cookies; - return(""); - } + Function GetPersistentCookies(&$cookies, $domain='', $secure_only=0) + { + $this->SavePersistentCookies($cookies, $domain, $secure_only); + } + + Function RestoreCookies($cookies, $clear=1) + { + $new_cookies=($clear ? array() : $this->cookies); + for($secure_cookies=0, Reset($cookies); $secure_cookiesSetError("invalid cookie secure value type (".serialize($secure).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + for($cookie_domain=0,Reset($cookies[$secure]);$cookie_domainSetError("invalid cookie domain value type (".serialize($domain_pattern).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + for(Reset($cookies[$secure][$domain_pattern]),$path_part=0;$path_partSetError("invalid cookie path value type (".serialize($path).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + for(Reset($cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookieSetError("invalid cookie expiry value type (".serialize($expires).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS)); + $new_cookies[$secure][$domain_pattern][$path][$cookie_name]=array( + "name"=>$cookie_name, + "value"=>$value, + "domain"=>$domain_pattern, + "path"=>$path, + "expires"=>$expires, + "secure"=>$secure + ); + } + } + } + } + $this->cookies=$new_cookies; + return(""); + } }; ?> \ No newline at end of file diff --git a/includes/jsmin-1.1.1.php b/includes/jsmin-1.1.1.php index 2f3bcc75b..e06129c36 100644 --- a/includes/jsmin-1.1.1.php +++ b/includes/jsmin-1.1.1.php @@ -1,291 +1,291 @@ - - * @copyright 2002 Douglas Crockford (jsmin.c) - * @copyright 2008 Ryan Grove (PHP port) - * @license http://opensource.org/licenses/mit-license.php MIT License - * @version 1.1.1 (2008-03-02) - * @link http://code.google.com/p/jsmin-php/ - */ - -class JSMin { - const ORD_LF = 10; - const ORD_SPACE = 32; - - protected $a = ''; - protected $b = ''; - protected $input = ''; - protected $inputIndex = 0; - protected $inputLength = 0; - protected $lookAhead = null; - protected $output = ''; - - // -- Public Static Methods -------------------------------------------------- - - public static function minify($js) { - $jsmin = new JSMin($js); - return $jsmin->min(); - } - - // -- Public Instance Methods ------------------------------------------------ - - public function __construct($input) { - $this->input = str_replace("\r\n", "\n", $input); - $this->inputLength = strlen($this->input); - } - - // -- Protected Instance Methods --------------------------------------------- - - protected function action($d) { - switch($d) { - case 1: - $this->output .= $this->a; - - case 2: - $this->a = $this->b; - - if ($this->a === "'" || $this->a === '"') { - for (;;) { - $this->output .= $this->a; - $this->a = $this->get(); - - if ($this->a === $this->b) { - break; - } - - if (ord($this->a) <= self::ORD_LF) { - throw new JSMinException('Unterminated string literal.'); - } - - if ($this->a === '\\') { - $this->output .= $this->a; - $this->a = $this->get(); - } - } - } - - case 3: - $this->b = $this->next(); - - if ($this->b === '/' && ( - $this->a === '(' || $this->a === ',' || $this->a === '=' || - $this->a === ':' || $this->a === '[' || $this->a === '!' || - $this->a === '&' || $this->a === '|' || $this->a === '?')) { - - $this->output .= $this->a . $this->b; - - for (;;) { - $this->a = $this->get(); - - if ($this->a === '/') { - break; - } elseif ($this->a === '\\') { - $this->output .= $this->a; - $this->a = $this->get(); - } elseif (ord($this->a) <= self::ORD_LF) { - throw new JSMinException('Unterminated regular expression '. - 'literal.'); - } - - $this->output .= $this->a; - } - - $this->b = $this->next(); - } - } - } - - protected function get() { - $c = $this->lookAhead; - $this->lookAhead = null; - - if ($c === null) { - if ($this->inputIndex < $this->inputLength) { - $c = $this->input[$this->inputIndex]; - $this->inputIndex += 1; - } else { - $c = null; - } - } - - if ($c === "\r") { - return "\n"; - } - - if ($c === null || $c === "\n" || ord($c) >= self::ORD_SPACE) { - return $c; - } - - return ' '; - } - - protected function isAlphaNum($c) { - return ord($c) > 126 || $c === '\\' || preg_match('/^[\w\$]$/', $c) === 1; - } - - protected function min() { - $this->a = "\n"; - $this->action(3); - - while ($this->a !== null) { - switch ($this->a) { - case ' ': - if ($this->isAlphaNum($this->b)) { - $this->action(1); - } else { - $this->action(2); - } - break; - - case "\n": - switch ($this->b) { - case '{': - case '[': - case '(': - case '+': - case '-': - $this->action(1); - break; - - case ' ': - $this->action(3); - break; - - default: - if ($this->isAlphaNum($this->b)) { - $this->action(1); - } - else { - $this->action(2); - } - } - break; - - default: - switch ($this->b) { - case ' ': - if ($this->isAlphaNum($this->a)) { - $this->action(1); - break; - } - - $this->action(3); - break; - - case "\n": - switch ($this->a) { - case '}': - case ']': - case ')': - case '+': - case '-': - case '"': - case "'": - $this->action(1); - break; - - default: - if ($this->isAlphaNum($this->a)) { - $this->action(1); - } - else { - $this->action(3); - } - } - break; - - default: - $this->action(1); - break; - } - } - } - - return $this->output; - } - - protected function next() { - $c = $this->get(); - - if ($c === '/') { - switch($this->peek()) { - case '/': - for (;;) { - $c = $this->get(); - - if (ord($c) <= self::ORD_LF) { - return $c; - } - } - - case '*': - $this->get(); - - for (;;) { - switch($this->get()) { - case '*': - if ($this->peek() === '/') { - $this->get(); - return ' '; - } - break; - - case null: - throw new JSMinException('Unterminated comment.'); - } - } - - default: - return $c; - } - } - - return $c; - } - - protected function peek() { - $this->lookAhead = $this->get(); - return $this->lookAhead; - } -} - -// -- Exceptions --------------------------------------------------------------- -class JSMinException extends Exception {} + + * @copyright 2002 Douglas Crockford (jsmin.c) + * @copyright 2008 Ryan Grove (PHP port) + * @license http://opensource.org/licenses/mit-license.php MIT License + * @version 1.1.1 (2008-03-02) + * @link http://code.google.com/p/jsmin-php/ + */ + +class JSMin { + const ORD_LF = 10; + const ORD_SPACE = 32; + + protected $a = ''; + protected $b = ''; + protected $input = ''; + protected $inputIndex = 0; + protected $inputLength = 0; + protected $lookAhead = null; + protected $output = ''; + + // -- Public Static Methods -------------------------------------------------- + + public static function minify($js) { + $jsmin = new JSMin($js); + return $jsmin->min(); + } + + // -- Public Instance Methods ------------------------------------------------ + + public function __construct($input) { + $this->input = str_replace("\r\n", "\n", $input); + $this->inputLength = strlen($this->input); + } + + // -- Protected Instance Methods --------------------------------------------- + + protected function action($d) { + switch($d) { + case 1: + $this->output .= $this->a; + + case 2: + $this->a = $this->b; + + if ($this->a === "'" || $this->a === '"') { + for (;;) { + $this->output .= $this->a; + $this->a = $this->get(); + + if ($this->a === $this->b) { + break; + } + + if (ord($this->a) <= self::ORD_LF) { + throw new JSMinException('Unterminated string literal.'); + } + + if ($this->a === '\\') { + $this->output .= $this->a; + $this->a = $this->get(); + } + } + } + + case 3: + $this->b = $this->next(); + + if ($this->b === '/' && ( + $this->a === '(' || $this->a === ',' || $this->a === '=' || + $this->a === ':' || $this->a === '[' || $this->a === '!' || + $this->a === '&' || $this->a === '|' || $this->a === '?')) { + + $this->output .= $this->a . $this->b; + + for (;;) { + $this->a = $this->get(); + + if ($this->a === '/') { + break; + } elseif ($this->a === '\\') { + $this->output .= $this->a; + $this->a = $this->get(); + } elseif (ord($this->a) <= self::ORD_LF) { + throw new JSMinException('Unterminated regular expression '. + 'literal.'); + } + + $this->output .= $this->a; + } + + $this->b = $this->next(); + } + } + } + + protected function get() { + $c = $this->lookAhead; + $this->lookAhead = null; + + if ($c === null) { + if ($this->inputIndex < $this->inputLength) { + $c = $this->input[$this->inputIndex]; + $this->inputIndex += 1; + } else { + $c = null; + } + } + + if ($c === "\r") { + return "\n"; + } + + if ($c === null || $c === "\n" || ord($c) >= self::ORD_SPACE) { + return $c; + } + + return ' '; + } + + protected function isAlphaNum($c) { + return ord($c) > 126 || $c === '\\' || preg_match('/^[\w\$]$/', $c) === 1; + } + + protected function min() { + $this->a = "\n"; + $this->action(3); + + while ($this->a !== null) { + switch ($this->a) { + case ' ': + if ($this->isAlphaNum($this->b)) { + $this->action(1); + } else { + $this->action(2); + } + break; + + case "\n": + switch ($this->b) { + case '{': + case '[': + case '(': + case '+': + case '-': + $this->action(1); + break; + + case ' ': + $this->action(3); + break; + + default: + if ($this->isAlphaNum($this->b)) { + $this->action(1); + } + else { + $this->action(2); + } + } + break; + + default: + switch ($this->b) { + case ' ': + if ($this->isAlphaNum($this->a)) { + $this->action(1); + break; + } + + $this->action(3); + break; + + case "\n": + switch ($this->a) { + case '}': + case ']': + case ')': + case '+': + case '-': + case '"': + case "'": + $this->action(1); + break; + + default: + if ($this->isAlphaNum($this->a)) { + $this->action(1); + } + else { + $this->action(3); + } + } + break; + + default: + $this->action(1); + break; + } + } + } + + return $this->output; + } + + protected function next() { + $c = $this->get(); + + if ($c === '/') { + switch($this->peek()) { + case '/': + for (;;) { + $c = $this->get(); + + if (ord($c) <= self::ORD_LF) { + return $c; + } + } + + case '*': + $this->get(); + + for (;;) { + switch($this->get()) { + case '*': + if ($this->peek() === '/') { + $this->get(); + return ' '; + } + break; + + case null: + throw new JSMinException('Unterminated comment.'); + } + } + + default: + return $c; + } + } + + return $c; + } + + protected function peek() { + $this->lookAhead = $this->get(); + return $this->lookAhead; + } +} + +// -- Exceptions --------------------------------------------------------------- +class JSMinException extends Exception {} ?> \ No newline at end of file diff --git a/includes/memcached-client.php b/includes/memcached-client.php index 7ea9dce9c..2aae718ef 100644 --- a/includes/memcached-client.php +++ b/includes/memcached-client.php @@ -75,27 +75,27 @@ class memcached // {{{ properties // {{{ public - // {{{ constants - // {{{ flags + // {{{ constants + // {{{ flags - /** - * Flag: indicates data is serialized - */ - const SERIALIZED = 1; + /** + * Flag: indicates data is serialized + */ + const SERIALIZED = 1; - /** - * Flag: indicates data is compressed - */ - const COMPRESSED = 2; + /** + * Flag: indicates data is compressed + */ + const COMPRESSED = 2; - // }}} + // }}} - /** - * Minimum savings to store data compressed - */ - const COMPRESSION_SAVINGS = 0.20; + /** + * Minimum savings to store data compressed + */ + const COMPRESSION_SAVINGS = 0.20; - // }}} + // }}} /** @@ -407,14 +407,14 @@ function get ($key) } if (!$this->_active) { - if (defined('MEDIAWIKI')) wfProfileOut( $fname ); + if (defined('MEDIAWIKI')) wfProfileOut( $fname ); return false; } $sock = $this->get_sock($key); if (!is_resource($sock)) { - if (defined('MEDIAWIKI')) wfProfileOut( $fname ); + if (defined('MEDIAWIKI')) wfProfileOut( $fname ); return false; } @@ -424,7 +424,7 @@ function get ($key) if (!$this->_safe_fwrite($sock, $cmd, strlen($cmd))) { $this->_dead_sock($sock); - if (defined('MEDIAWIKI')) wfProfileOut( $fname ); + if (defined('MEDIAWIKI')) wfProfileOut( $fname ); return false; } @@ -801,7 +801,7 @@ function get_sock ($key) if (is_resource($sock)) { $this->_flush_read_buffer($sock); return $sock; - } + } $hv = $this->_hashfunc( $hv . $realkey ); } diff --git a/includes/pqp/classes/Console.php b/includes/pqp/classes/Console.php index 965adc8ea..e92de6518 100644 --- a/includes/pqp/classes/Console.php +++ b/includes/pqp/classes/Console.php @@ -14,77 +14,77 @@ - - - - - - - - - - - - - - - - - - - - - */ class Console { - - /*----------------------------------- - LOG A VARIABLE TO CONSOLE - ------------------------------------*/ - - public static function log($data) { - $logItem = array( - "data" => $data, - "type" => 'log' - ); - $GLOBALS['debugger_logs']['console'][] = $logItem; - $GLOBALS['debugger_logs']['logCount'] += 1; - } - - /*--------------------------------------------------- - LOG MEMORY USAGE OF VARIABLE OR ENTIRE SCRIPT - -----------------------------------------------------*/ - - public function logMemory($object = false, $name = 'PHP') { - $memory = memory_get_usage(); - if($object) $memory = strlen(serialize($object)); - $logItem = array( - "data" => $memory, - "type" => 'memory', - "name" => $name, - "dataType" => gettype($object) - ); - $GLOBALS['debugger_logs']['console'][] = $logItem; - $GLOBALS['debugger_logs']['memoryCount'] += 1; - } - - /*----------------------------------- - LOG A PHP EXCEPTION OBJECT - ------------------------------------*/ - - public function logError($exception, $message) { - $logItem = array( - "data" => $message, - "type" => 'error', - "file" => $exception->getFile(), - "line" => $exception->getLine() - ); - $GLOBALS['debugger_logs']['console'][] = $logItem; - $GLOBALS['debugger_logs']['errorCount'] += 1; - } - - /*------------------------------------ - POINT IN TIME SPEED SNAPSHOT - -------------------------------------*/ - - public function logSpeed($name = 'Point in Time') { - $logItem = array( - "data" => PhpQuickProfiler::getMicroTime(), - "type" => 'speed', - "name" => $name - ); - $GLOBALS['debugger_logs']['console'][] = $logItem; - $GLOBALS['debugger_logs']['speedCount'] += 1; - } - - /*----------------------------------- - SET DEFAULTS & RETURN LOGS - ------------------------------------*/ - - public function getLogs() { - if(!$GLOBALS['debugger_logs']['memoryCount']) $GLOBALS['debugger_logs']['memoryCount'] = 0; - if(!$GLOBALS['debugger_logs']['logCount']) $GLOBALS['debugger_logs']['logCount'] = 0; - if(!$GLOBALS['debugger_logs']['speedCount']) $GLOBALS['debugger_logs']['speedCount'] = 0; - if(!$GLOBALS['debugger_logs']['errorCount']) $GLOBALS['debugger_logs']['errorCount'] = 0; - return $GLOBALS['debugger_logs']; - } + + /*----------------------------------- + LOG A VARIABLE TO CONSOLE + ------------------------------------*/ + + public static function log($data) { + $logItem = array( + "data" => $data, + "type" => 'log' + ); + $GLOBALS['debugger_logs']['console'][] = $logItem; + $GLOBALS['debugger_logs']['logCount'] += 1; + } + + /*--------------------------------------------------- + LOG MEMORY USAGE OF VARIABLE OR ENTIRE SCRIPT + -----------------------------------------------------*/ + + public function logMemory($object = false, $name = 'PHP') { + $memory = memory_get_usage(); + if($object) $memory = strlen(serialize($object)); + $logItem = array( + "data" => $memory, + "type" => 'memory', + "name" => $name, + "dataType" => gettype($object) + ); + $GLOBALS['debugger_logs']['console'][] = $logItem; + $GLOBALS['debugger_logs']['memoryCount'] += 1; + } + + /*----------------------------------- + LOG A PHP EXCEPTION OBJECT + ------------------------------------*/ + + public function logError($exception, $message) { + $logItem = array( + "data" => $message, + "type" => 'error', + "file" => $exception->getFile(), + "line" => $exception->getLine() + ); + $GLOBALS['debugger_logs']['console'][] = $logItem; + $GLOBALS['debugger_logs']['errorCount'] += 1; + } + + /*------------------------------------ + POINT IN TIME SPEED SNAPSHOT + -------------------------------------*/ + + public function logSpeed($name = 'Point in Time') { + $logItem = array( + "data" => PhpQuickProfiler::getMicroTime(), + "type" => 'speed', + "name" => $name + ); + $GLOBALS['debugger_logs']['console'][] = $logItem; + $GLOBALS['debugger_logs']['speedCount'] += 1; + } + + /*----------------------------------- + SET DEFAULTS & RETURN LOGS + ------------------------------------*/ + + public function getLogs() { + if(!$GLOBALS['debugger_logs']['memoryCount']) $GLOBALS['debugger_logs']['memoryCount'] = 0; + if(!$GLOBALS['debugger_logs']['logCount']) $GLOBALS['debugger_logs']['logCount'] = 0; + if(!$GLOBALS['debugger_logs']['speedCount']) $GLOBALS['debugger_logs']['speedCount'] = 0; + if(!$GLOBALS['debugger_logs']['errorCount']) $GLOBALS['debugger_logs']['errorCount'] = 0; + return $GLOBALS['debugger_logs']; + } } ?> \ No newline at end of file diff --git a/includes/pqp/classes/MySqlDatabase.php b/includes/pqp/classes/MySqlDatabase.php index 76dc2a8a1..769daaf62 100644 --- a/includes/pqp/classes/MySqlDatabase.php +++ b/includes/pqp/classes/MySqlDatabase.php @@ -15,101 +15,101 @@ class MySqlDatabase { - private $host; - private $user; - private $password; - private $database; - public $queryCount = 0; - public $queries = array(); - public $conn; - - /*------------------------------------ - CONFIG CONNECTION - ------------------------------------*/ - - function __construct($host, $user, $password) { - $this->host = $host; - $this->user = $user; - $this->password = $password; - } - - function connect($new = false) { - $this->conn = mysqli_connect($this->host, $this->user, $this->password, $new); - if(!$this->conn) { - throw new Exception('We\'re working on a few connection issues.'); - } - } - - function changeDatabase($database) { - $this->database = $database; - if($this->conn) { - if(!mysqli_select_db($this->conn, $database)) { - throw new CustomException('We\'re working on a few connection issues.'); - } - } - } - - function lazyLoadConnection() { - $this->connect(true); - if($this->database) $this->changeDatabase($this->database); - } - - /*----------------------------------- - QUERY - ------------------------------------*/ - - function query($sql) { - if(!$this->conn) $this->lazyLoadConnection(); - $start = $this->getTime(); - $rs = mysqli_query($this->conn, $sql); - $this->queryCount += 1; - $this->logQuery($sql, $start); - if(!$rs) { - throw new Exception('Could not execute query.'); - } - return $rs; - } - - /*----------------------------------- - DEBUGGING - ------------------------------------*/ - - function logQuery($sql, $start) { - $query = array( - 'sql' => $sql, - 'time' => ($this->getTime() - $start)*1000 - ); - array_push($this->queries, $query); - } - - function getTime() { - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $start = $time; - return $start; - } - - public function getReadableTime($time) { - $ret = $time; - $formatter = 0; - $formats = array('ms', 's', 'm'); - if($time >= 1000 && $time < 60000) { - $formatter = 1; - $ret = ($time / 1000); - } - if($time >= 60000) { - $formatter = 2; - $ret = ($time / 1000) / 60; - } - $ret = number_format($ret,3,'.','') . ' ' . $formats[$formatter]; - return $ret; - } - - function __destruct() { - @mysqli_close($this->conn); - } - + private $host; + private $user; + private $password; + private $database; + public $queryCount = 0; + public $queries = array(); + public $conn; + + /*------------------------------------ + CONFIG CONNECTION + ------------------------------------*/ + + function __construct($host, $user, $password) { + $this->host = $host; + $this->user = $user; + $this->password = $password; + } + + function connect($new = false) { + $this->conn = mysqli_connect($this->host, $this->user, $this->password, $new); + if(!$this->conn) { + throw new Exception('We\'re working on a few connection issues.'); + } + } + + function changeDatabase($database) { + $this->database = $database; + if($this->conn) { + if(!mysqli_select_db($this->conn, $database)) { + throw new CustomException('We\'re working on a few connection issues.'); + } + } + } + + function lazyLoadConnection() { + $this->connect(true); + if($this->database) $this->changeDatabase($this->database); + } + + /*----------------------------------- + QUERY + ------------------------------------*/ + + function query($sql) { + if(!$this->conn) $this->lazyLoadConnection(); + $start = $this->getTime(); + $rs = mysqli_query($this->conn, $sql); + $this->queryCount += 1; + $this->logQuery($sql, $start); + if(!$rs) { + throw new Exception('Could not execute query.'); + } + return $rs; + } + + /*----------------------------------- + DEBUGGING + ------------------------------------*/ + + function logQuery($sql, $start) { + $query = array( + 'sql' => $sql, + 'time' => ($this->getTime() - $start)*1000 + ); + array_push($this->queries, $query); + } + + function getTime() { + $time = microtime(); + $time = explode(' ', $time); + $time = $time[1] + $time[0]; + $start = $time; + return $start; + } + + public function getReadableTime($time) { + $ret = $time; + $formatter = 0; + $formats = array('ms', 's', 'm'); + if($time >= 1000 && $time < 60000) { + $formatter = 1; + $ret = ($time / 1000); + } + if($time >= 60000) { + $formatter = 2; + $ret = ($time / 1000) / 60; + } + $ret = number_format($ret,3,'.','') . ' ' . $formats[$formatter]; + return $ret; + } + + function __destruct() { + @mysqli_close($this->conn); + } + } ?> diff --git a/includes/pqp/classes/PhpQuickProfiler.php b/includes/pqp/classes/PhpQuickProfiler.php index 168f19c9b..09b819c9b 100644 --- a/includes/pqp/classes/PhpQuickProfiler.php +++ b/includes/pqp/classes/PhpQuickProfiler.php @@ -16,189 +16,189 @@ - - - - - - - - - - - - - - - - - - - - - */ class PhpQuickProfiler { - - public $output = array(); - public $config = ''; - - public function __construct($startTime, $config = 'pqp/') { - $this->startTime = $startTime; - $this->config = $config; - require_once($config.'classes/Console.php'); - } - - /*------------------------------------------- - FORMAT THE DIFFERENT TYPES OF LOGS - -------------------------------------------*/ - - public function gatherConsoleData() { - $logs = Console::getLogs(); - if($logs['console']) { - foreach($logs['console'] as $key => $log) { - if($log['type'] == 'log') { - $logs['console'][$key]['data'] = print_r($log['data'], true); - } - elseif($log['type'] == 'memory') { - $logs['console'][$key]['data'] = $this->getReadableFileSize($log['data']); - } - elseif($log['type'] == 'speed') { - $logs['console'][$key]['data'] = $this->getReadableTime(($log['data'] - $this->startTime)*1000); - } - } - } - $this->output['logs'] = $logs; - } - - /*------------------------------------------- - AGGREGATE DATA ON THE FILES INCLUDED - -------------------------------------------*/ - - public function gatherFileData() { - $files = get_included_files(); - $fileList = array(); - $fileTotals = array( - "count" => count($files), - "size" => 0, - "largest" => 0, - ); - - foreach($files as $key => $file) { - $size = filesize($file); - $fileList[] = array( - 'name' => $file, - 'size' => $this->getReadableFileSize($size) - ); - $fileTotals['size'] += $size; - if($size > $fileTotals['largest']) $fileTotals['largest'] = $size; - } - - $fileTotals['size'] = $this->getReadableFileSize($fileTotals['size']); - $fileTotals['largest'] = $this->getReadableFileSize($fileTotals['largest']); - $this->output['files'] = $fileList; - $this->output['fileTotals'] = $fileTotals; - } - - /*------------------------------------------- - MEMORY USAGE AND MEMORY AVAILABLE - -------------------------------------------*/ - - public function gatherMemoryData() { - $memoryTotals = array(); - $memoryTotals['used'] = $this->getReadableFileSize(memory_get_peak_usage()); - $memoryTotals['total'] = ini_get("memory_limit"); - $this->output['memoryTotals'] = $memoryTotals; - } - - /*-------------------------------------------------------- - QUERY DATA -- DATABASE OBJECT WITH LOGGING REQUIRED - ----------------------------------------------------------*/ - - public function gatherQueryData() { - $queryTotals = array(); - $queryTotals['count'] = 0; - $queryTotals['time'] = 0; - $queries = array(); - - if($this->db != '') { - $queryTotals['count'] += $this->db->queryCount; - foreach($this->db->queries as $key => $query) { - $query = $this->attemptToExplainQuery($query); - $queryTotals['time'] += $query['time']; - $query['time'] = $this->getReadableTime($query['time']); - $queries[] = $query; - } - } - - $queryTotals['time'] = $this->getReadableTime($queryTotals['time']); - $this->output['queries'] = $queries; - $this->output['queryTotals'] = $queryTotals; - } - - /*-------------------------------------------------------- - CALL SQL EXPLAIN ON THE QUERY TO FIND MORE INFO - ----------------------------------------------------------*/ - - function attemptToExplainQuery($query) { - try { - $sql = 'EXPLAIN '.$query['sql']; - $rs = $this->db->query($sql); - } - catch(Exception $e) {} - if($rs) { - $row = mysqli_fetch_array($rs, MYSQLI_ASSOC); - $query['explain'] = $row; - } - return $query; - } - - /*------------------------------------------- - SPEED DATA FOR ENTIRE PAGE LOAD - -------------------------------------------*/ - - public function gatherSpeedData() { - $speedTotals = array(); - $speedTotals['total'] = $this->getReadableTime(($this->getMicroTime() - $this->startTime)*1000); - $speedTotals['allowed'] = ini_get("max_execution_time"); - $this->output['speedTotals'] = $speedTotals; - } - - /*------------------------------------------- - HELPER FUNCTIONS TO FORMAT DATA - -------------------------------------------*/ - - function getMicroTime() { - $time = microtime(); - $time = explode(' ', $time); - return $time[1] + $time[0]; - } - - public function getReadableFileSize($size, $retstring = null) { - // adapted from code at http://aidanlister.com/repos/v/function.size_readable.php - $sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - - if ($retstring === null) { $retstring = '%01.2f %s'; } - - $lastsizestring = end($sizes); - - foreach ($sizes as $sizestring) { - if ($size < 1024) { break; } - if ($sizestring != $lastsizestring) { $size /= 1024; } - } - if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional - return sprintf($retstring, $size, $sizestring); - } - - public function getReadableTime($time) { - $ret = $time; - $formatter = 0; - $formats = array('ms', 's', 'm'); - if($time >= 1000 && $time < 60000) { - $formatter = 1; - $ret = ($time / 1000); - } - if($time >= 60000) { - $formatter = 2; - $ret = ($time / 1000) / 60; - } - $ret = number_format($ret,3,'.','') . ' ' . $formats[$formatter]; - return $ret; - } - - /*--------------------------------------------------------- - DISPLAY TO THE SCREEN -- CALL WHEN CODE TERMINATING - -----------------------------------------------------------*/ - - public function display($db = '', $master_db = '') { - $this->db = $db; - $this->master_db = $master_db; - $this->gatherConsoleData(); - $this->gatherFileData(); - $this->gatherMemoryData(); - $this->gatherQueryData(); - $this->gatherSpeedData(); - require_once($this->config.'display.php'); - displayPqp($this->output, OWA_PUBLIC_URL.'includes/pqp/'); - } - + + public $output = array(); + public $config = ''; + + public function __construct($startTime, $config = 'pqp/') { + $this->startTime = $startTime; + $this->config = $config; + require_once($config.'classes/Console.php'); + } + + /*------------------------------------------- + FORMAT THE DIFFERENT TYPES OF LOGS + -------------------------------------------*/ + + public function gatherConsoleData() { + $logs = Console::getLogs(); + if($logs['console']) { + foreach($logs['console'] as $key => $log) { + if($log['type'] == 'log') { + $logs['console'][$key]['data'] = print_r($log['data'], true); + } + elseif($log['type'] == 'memory') { + $logs['console'][$key]['data'] = $this->getReadableFileSize($log['data']); + } + elseif($log['type'] == 'speed') { + $logs['console'][$key]['data'] = $this->getReadableTime(($log['data'] - $this->startTime)*1000); + } + } + } + $this->output['logs'] = $logs; + } + + /*------------------------------------------- + AGGREGATE DATA ON THE FILES INCLUDED + -------------------------------------------*/ + + public function gatherFileData() { + $files = get_included_files(); + $fileList = array(); + $fileTotals = array( + "count" => count($files), + "size" => 0, + "largest" => 0, + ); + + foreach($files as $key => $file) { + $size = filesize($file); + $fileList[] = array( + 'name' => $file, + 'size' => $this->getReadableFileSize($size) + ); + $fileTotals['size'] += $size; + if($size > $fileTotals['largest']) $fileTotals['largest'] = $size; + } + + $fileTotals['size'] = $this->getReadableFileSize($fileTotals['size']); + $fileTotals['largest'] = $this->getReadableFileSize($fileTotals['largest']); + $this->output['files'] = $fileList; + $this->output['fileTotals'] = $fileTotals; + } + + /*------------------------------------------- + MEMORY USAGE AND MEMORY AVAILABLE + -------------------------------------------*/ + + public function gatherMemoryData() { + $memoryTotals = array(); + $memoryTotals['used'] = $this->getReadableFileSize(memory_get_peak_usage()); + $memoryTotals['total'] = ini_get("memory_limit"); + $this->output['memoryTotals'] = $memoryTotals; + } + + /*-------------------------------------------------------- + QUERY DATA -- DATABASE OBJECT WITH LOGGING REQUIRED + ----------------------------------------------------------*/ + + public function gatherQueryData() { + $queryTotals = array(); + $queryTotals['count'] = 0; + $queryTotals['time'] = 0; + $queries = array(); + + if($this->db != '') { + $queryTotals['count'] += $this->db->queryCount; + foreach($this->db->queries as $key => $query) { + $query = $this->attemptToExplainQuery($query); + $queryTotals['time'] += $query['time']; + $query['time'] = $this->getReadableTime($query['time']); + $queries[] = $query; + } + } + + $queryTotals['time'] = $this->getReadableTime($queryTotals['time']); + $this->output['queries'] = $queries; + $this->output['queryTotals'] = $queryTotals; + } + + /*-------------------------------------------------------- + CALL SQL EXPLAIN ON THE QUERY TO FIND MORE INFO + ----------------------------------------------------------*/ + + function attemptToExplainQuery($query) { + try { + $sql = 'EXPLAIN '.$query['sql']; + $rs = $this->db->query($sql); + } + catch(Exception $e) {} + if($rs) { + $row = mysqli_fetch_array($rs, MYSQLI_ASSOC); + $query['explain'] = $row; + } + return $query; + } + + /*------------------------------------------- + SPEED DATA FOR ENTIRE PAGE LOAD + -------------------------------------------*/ + + public function gatherSpeedData() { + $speedTotals = array(); + $speedTotals['total'] = $this->getReadableTime(($this->getMicroTime() - $this->startTime)*1000); + $speedTotals['allowed'] = ini_get("max_execution_time"); + $this->output['speedTotals'] = $speedTotals; + } + + /*------------------------------------------- + HELPER FUNCTIONS TO FORMAT DATA + -------------------------------------------*/ + + function getMicroTime() { + $time = microtime(); + $time = explode(' ', $time); + return $time[1] + $time[0]; + } + + public function getReadableFileSize($size, $retstring = null) { + // adapted from code at http://aidanlister.com/repos/v/function.size_readable.php + $sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); + + if ($retstring === null) { $retstring = '%01.2f %s'; } + + $lastsizestring = end($sizes); + + foreach ($sizes as $sizestring) { + if ($size < 1024) { break; } + if ($sizestring != $lastsizestring) { $size /= 1024; } + } + if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional + return sprintf($retstring, $size, $sizestring); + } + + public function getReadableTime($time) { + $ret = $time; + $formatter = 0; + $formats = array('ms', 's', 'm'); + if($time >= 1000 && $time < 60000) { + $formatter = 1; + $ret = ($time / 1000); + } + if($time >= 60000) { + $formatter = 2; + $ret = ($time / 1000) / 60; + } + $ret = number_format($ret,3,'.','') . ' ' . $formats[$formatter]; + return $ret; + } + + /*--------------------------------------------------------- + DISPLAY TO THE SCREEN -- CALL WHEN CODE TERMINATING + -----------------------------------------------------------*/ + + public function display($db = '', $master_db = '') { + $this->db = $db; + $this->master_db = $master_db; + $this->gatherConsoleData(); + $this->gatherFileData(); + $this->gatherMemoryData(); + $this->gatherQueryData(); + $this->gatherSpeedData(); + require_once($this->config.'display.php'); + displayPqp($this->output, OWA_PUBLIC_URL.'includes/pqp/'); + } + } ?> \ No newline at end of file diff --git a/includes/pqp/css/pQp.css b/includes/pqp/css/pQp.css index 8d9c68bb0..fb4f63341 100644 --- a/includes/pqp/css/pQp.css +++ b/includes/pqp/css/pQp.css @@ -9,53 +9,53 @@ - - - - - - - - - - - - - - - - - - - - - */ .pQp{ - width:100%; - text-align:center; - position:fixed; - bottom:0; + width:100%; + text-align:center; + position:fixed; + bottom:0; } * html .pQp{ - position:absolute; + position:absolute; } .pQp *{ - margin:0; - padding:0; - border:none; + margin:0; + padding:0; + border:none; } #pQp{ - margin:0 auto; - width:85%; - min-width:960px; - background-color:#222; - border:12px solid #000; - border-bottom:none; - font-family:"Lucida Grande", Tahoma, Arial, sans-serif; - -webkit-border-top-left-radius:15px; - -webkit-border-top-right-radius:15px; - -moz-border-radius-topleft:15px; - -moz-border-radius-topright:15px; + margin:0 auto; + width:85%; + min-width:960px; + background-color:#222; + border:12px solid #000; + border-bottom:none; + font-family:"Lucida Grande", Tahoma, Arial, sans-serif; + -webkit-border-top-left-radius:15px; + -webkit-border-top-right-radius:15px; + -moz-border-radius-topleft:15px; + -moz-border-radius-topright:15px; } #pQp .pqp-box h3{ - font-weight:normal; - line-height:200px; - padding:0 15px; - color:#fff; + font-weight:normal; + line-height:200px; + padding:0 15px; + color:#fff; } .pQp, .pQp td{ - color:#444; + color:#444; } /* ----- IDS ----- */ #pqp-metrics{ - background:#000; - width:100%; + background:#000; + width:100%; } #pqp-console, #pqp-speed, #pqp-queries, #pqp-memory, #pqp-files{ - background:url(../images/overlay.gif); - border-top:1px solid #ccc; - height:200px; - overflow:auto; + background:url(../images/overlay.gif); + border-top:1px solid #ccc; + height:200px; + overflow:auto; } /* ----- Colors ----- */ @@ -69,338 +69,338 @@ /* ----- Logic ----- */ #pQp, #pqp-console, #pqp-speed, #pqp-queries, #pqp-memory, #pqp-files{ - display:none; + display:none; } .pQp .console, .pQp .speed, .pQp .queries, .pQp .memory, .pQp .files{ - display:block !important; + display:block !important; } .pQp .console #pqp-console, .pQp .speed #pqp-speed, .pQp .queries #pqp-queries, .pQp .memory #pqp-memory, .pQp .files #pqp-files{ - display:block; + display:block; } .console td.green, .speed td.blue, .queries td.purple, .memory td.orange, .files td.red{ - background:#222 !important; - border-bottom:6px solid #fff !important; - cursor:default !important; + background:#222 !important; + border-bottom:6px solid #fff !important; + cursor:default !important; } .tallDetails #pQp .pqp-box{ - height:500px; + height:500px; } .tallDetails #pQp .pqp-box h3{ - line-height:500px; + line-height:500px; } .hideDetails #pQp .pqp-box{ - display:none !important; + display:none !important; } .hideDetails #pqp-footer{ - border-top:1px dotted #444; + border-top:1px dotted #444; } .hideDetails #pQp #pqp-metrics td{ - height:50px; - background:#000 !important; - border-bottom:none !important; - cursor:default !important; + height:50px; + background:#000 !important; + border-bottom:none !important; + cursor:default !important; } .hideDetails #pQp var{ - font-size:18px; - margin:0 0 2px 0; + font-size:18px; + margin:0 0 2px 0; } .hideDetails #pQp h4{ - font-size:10px; + font-size:10px; } .hideDetails .heightToggle{ - visibility:hidden; + visibility:hidden; } /* ----- Metrics ----- */ #pqp-metrics td{ - height:80px; - width:20%; - text-align:center; - cursor:pointer; - border:1px solid #000; - border-bottom:6px solid #444; - -webkit-border-top-left-radius:10px; - -moz-border-radius-topleft:10px; - -webkit-border-top-right-radius:10px; - -moz-border-radius-topright:10px; + height:80px; + width:20%; + text-align:center; + cursor:pointer; + border:1px solid #000; + border-bottom:6px solid #444; + -webkit-border-top-left-radius:10px; + -moz-border-radius-topleft:10px; + -webkit-border-top-right-radius:10px; + -moz-border-radius-topright:10px; } #pqp-metrics td:hover{ - background:#222; - border-bottom:6px solid #777; + background:#222; + border-bottom:6px solid #777; } #pqp-metrics .green{ - border-left:none; + border-left:none; } #pqp-metrics .red{ - border-right:none; + border-right:none; } #pqp-metrics h4{ - text-shadow:#000 1px 1px 1px; + text-shadow:#000 1px 1px 1px; } .side var{ - text-shadow:#444 1px 1px 1px; + text-shadow:#444 1px 1px 1px; } .pQp var{ - font-size:23px; - font-weight:bold; - font-style:normal; - margin:0 0 3px 0; - display:block; + font-size:23px; + font-weight:bold; + font-style:normal; + margin:0 0 3px 0; + display:block; } .pQp h4{ - font-size:12px; - color:#fff; - margin:0 0 4px 0; + font-size:12px; + color:#fff; + margin:0 0 4px 0; } /* ----- Main ----- */ .pQp .main{ - width:80%; + width:80%; } *+html .pQp .main{ - width:78%; + width:78%; } * html .pQp .main{ - width:77%; + width:77%; } .pQp .main td{ - padding:7px 15px; - text-align:left; - background:#151515; - border-left:1px solid #333; - border-right:1px solid #333; - border-bottom:1px dotted #323232; - color:#FFF; + padding:7px 15px; + text-align:left; + background:#151515; + border-left:1px solid #333; + border-right:1px solid #333; + border-bottom:1px dotted #323232; + color:#FFF; } .pQp .main td, pre{ - font-family:Monaco, "Consolas", "Lucida Console", "Courier New", monospace; - font-size:11px; + font-family:Monaco, "Consolas", "Lucida Console", "Courier New", monospace; + font-size:11px; } .pQp .main td.alt{ - background:#111; + background:#111; } .pQp .main tr.alt td{ - background:#2E2E2E; - border-top:1px dotted #4E4E4E; + background:#2E2E2E; + border-top:1px dotted #4E4E4E; } .pQp .main tr.alt td.alt{ - background:#333; + background:#333; } .pQp .main td b{ - float:right; - font-weight:normal; - color:#E6F387; + float:right; + font-weight:normal; + color:#E6F387; } .pQp .main td:hover{ - background:#2E2E2E; + background:#2E2E2E; } /* ----- Side ----- */ .pQp .side{ - float:left; - width:20%; - background:#000; - color:#fff; - -webkit-border-bottom-left-radius:30px; - -moz-border-radius-bottomleft:30px; - text-align:center; + float:left; + width:20%; + background:#000; + color:#fff; + -webkit-border-bottom-left-radius:30px; + -moz-border-radius-bottomleft:30px; + text-align:center; } .pQp .side td{ - padding:10px 0 5px 0; - background:url(../images/side.png) repeat-y right; + padding:10px 0 5px 0; + background:url(../images/side.png) repeat-y right; } .pQp .side var{ - color:#fff; - font-size:15px; + color:#fff; + font-size:15px; } .pQp .side h4{ - font-weight:normal; - color:#F4FCCA; - font-size:11px; + font-weight:normal; + color:#F4FCCA; + font-size:11px; } /* ----- Console ----- */ #pqp-console .side td{ - padding:12px 0; + padding:12px 0; } #pqp-console .side td.alt1{ - background:#588E13; - width:51%; + background:#588E13; + width:51%; } #pqp-console .side td.alt2{ - background-color:#B72F09; + background-color:#B72F09; } #pqp-console .side td.alt3{ - background:#D28C00; - border-bottom:1px solid #9C6800; - border-left:1px solid #9C6800; - -webkit-border-bottom-left-radius:30px; - -moz-border-radius-bottomleft:30px; + background:#D28C00; + border-bottom:1px solid #9C6800; + border-left:1px solid #9C6800; + -webkit-border-bottom-left-radius:30px; + -moz-border-radius-bottomleft:30px; } #pqp-console .side td.alt4{ - background-color:#3769A0; - border-bottom:1px solid #274B74; + background-color:#3769A0; + border-bottom:1px solid #274B74; } #pqp-console .main table{ - width:100%; + width:100%; } #pqp-console td div{ - width:100%; - overflow:hidden; + width:100%; + overflow:hidden; } #pqp-console td.type{ - font-family:"Lucida Grande", Tahoma, Arial, sans-serif; - text-align:center; - text-transform: uppercase; - font-size:9px; - padding-top:9px; - color:#F4FCCA; - vertical-align:top; - width:40px; + font-family:"Lucida Grande", Tahoma, Arial, sans-serif; + text-align:center; + text-transform: uppercase; + font-size:9px; + padding-top:9px; + color:#F4FCCA; + vertical-align:top; + width:40px; } .pQp .log-log td.type{ - background:#47740D !important; + background:#47740D !important; } .pQp .log-error td.type{ - background:#9B2700 !important; + background:#9B2700 !important; } .pQp .log-memory td.type{ - background:#D28C00 !important; + background:#D28C00 !important; } .pQp .log-speed td.type{ - background:#2B5481 !important; + background:#2B5481 !important; } .pQp .log-log pre{ - color:#999; + color:#999; } .pQp .log-log td:hover pre{ - color:#fff; + color:#fff; } .pQp .log-memory em, .pQp .log-speed em{ - float:left; - font-style:normal; - display:block; - color:#fff; + float:left; + font-style:normal; + display:block; + color:#fff; } .pQp .log-memory pre, .pQp .log-speed pre{ - float:right; - white-space: normal; - display:block; - color:#FFFD70; + float:right; + white-space: normal; + display:block; + color:#FFFD70; } /* ----- Speed ----- */ #pqp-speed .side td{ - padding:12px 0; + padding:12px 0; } #pqp-speed .side{ - background-color:#3769A0; + background-color:#3769A0; } #pqp-speed .side td.alt{ - background-color:#2B5481; - border-bottom:1px solid #1E3C5C; - border-left:1px solid #1E3C5C; - -webkit-border-bottom-left-radius:30px; - -moz-border-radius-bottomleft:30px; + background-color:#2B5481; + border-bottom:1px solid #1E3C5C; + border-left:1px solid #1E3C5C; + -webkit-border-bottom-left-radius:30px; + -moz-border-radius-bottomleft:30px; } /* ----- Queries ----- */ #pqp-queries .side{ - background-color:#953FA1; - border-bottom:1px solid #662A6E; - border-left:1px solid #662A6E; + background-color:#953FA1; + border-bottom:1px solid #662A6E; + border-left:1px solid #662A6E; } #pqp-queries .side td.alt{ - background-color:#7B3384; + background-color:#7B3384; } #pqp-queries .main b{ - float:none; + float:none; } #pqp-queries .main em{ - display:block; - padding:2px 0 0 0; - font-style:normal; - color:#aaa; + display:block; + padding:2px 0 0 0; + font-style:normal; + color:#aaa; } /* ----- Memory ----- */ #pqp-memory .side td{ - padding:12px 0; + padding:12px 0; } #pqp-memory .side{ - background-color:#C48200; + background-color:#C48200; } #pqp-memory .side td.alt{ - background-color:#AC7200; - border-bottom:1px solid #865900; - border-left:1px solid #865900; - -webkit-border-bottom-left-radius:30px; - -moz-border-radius-bottomleft:30px; + background-color:#AC7200; + border-bottom:1px solid #865900; + border-left:1px solid #865900; + -webkit-border-bottom-left-radius:30px; + -moz-border-radius-bottomleft:30px; } /* ----- Files ----- */ #pqp-files .side{ - background-color:#B72F09; - border-bottom:1px solid #7C1F00; - border-left:1px solid #7C1F00; + background-color:#B72F09; + border-bottom:1px solid #7C1F00; + border-left:1px solid #7C1F00; } #pqp-files .side td.alt{ - background-color:#9B2700; + background-color:#9B2700; } /* ----- Footer ----- */ #pqp-footer{ - width:100%; - background:#000; - font-size:11px; - border-top:1px solid #ccc; + width:100%; + background:#000; + font-size:11px; + border-top:1px solid #ccc; } #pqp-footer td{ - padding:0 !important; - border:none !important; + padding:0 !important; + border:none !important; } #pqp-footer strong{ - color:#fff; + color:#fff; } #pqp-footer a{ - color:#999; - padding:5px 10px; - text-decoration:none; + color:#999; + padding:5px 10px; + text-decoration:none; } #pqp-footer .credit{ - width:20%; - text-align:left; + width:20%; + text-align:left; } #pqp-footer .actions{ - width:80%; - text-align:right; + width:80%; + text-align:right; } #pqp-footer .actions a{ - float:right; - width:auto; + float:right; + width:auto; } #pqp-footer a:hover, #pqp-footer a:hover strong, #pqp-footer a:hover b{ - background:#fff; - color:blue !important; - text-decoration:underline; + background:#fff; + color:blue !important; + text-decoration:underline; } #pqp-footer a:active, #pqp-footer a:active strong, #pqp-footer a:active b{ - background:#ECF488; - color:green !important; + background:#ECF488; + color:green !important; } \ No newline at end of file diff --git a/includes/pqp/display.php b/includes/pqp/display.php index 9a1ee93bc..d7c6a972e 100644 --- a/includes/pqp/display.php +++ b/includes/pqp/display.php @@ -16,114 +16,114 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ function displayPqp($output, $config) { - + $cssUrl = $config.'css/pQp.css'; - + echo << JAVASCRIPT; @@ -139,26 +139,26 @@ function addEvent( obj, type, fn ) {
- - - - - + + + + +
- $logCount -

Console

-
- $speedTotal -

Load Time

-
- $queryCount Queries -

Database

-
- $memoryUsed -

Memory Used

-
- {$fileCount} Files -

Included

-
+ $logCount +

Console

+
+ $speedTotal +

Load Time

+
+ $queryCount Queries +

Database

+
+ $memoryUsed +

Memory Used

+
+ {$fileCount} Files +

Included

+
PQPTABS; @@ -166,45 +166,45 @@ function addEvent( obj, type, fn ) { echo '
'; if($logCount == 0) { - echo '

This panel has no log items.

'; + echo '

This panel has no log items.

'; } else { - echo ' - - - - - - - - -
'.$output['logs']['logCount'].'

Logs

'.$output['logs']['errorCount'].'

Errors

'.$output['logs']['memoryCount'].'

Memory

'.$output['logs']['speedCount'].'

Speed

- '; - - $class = ''; - foreach($output['logs']['console'] as $log) { - echo ' - - '; - if($class == '') $class = 'alt'; - else $class = ''; - } - - echo '
'.$log['type'].''; - if($log['type'] == 'log') { - echo '
'.$log['data'].'
'; - } - elseif($log['type'] == 'memory') { - echo '
'.$log['data'].'
'.$log['dataType'].': '.$log['name'].'
'; - } - elseif($log['type'] == 'speed') { - echo '
'.$log['data'].'
'.$log['name'].'
'; - } - elseif($log['type'] == 'error') { - echo '
Line '.$log['line'].' : '.$log['data'].'
'.$log['file'].'
'; - } - - echo '
'; + echo ' + + + + + + + + +
'.$output['logs']['logCount'].'

Logs

'.$output['logs']['errorCount'].'

Errors

'.$output['logs']['memoryCount'].'

Memory

'.$output['logs']['speedCount'].'

Speed

+ '; + + $class = ''; + foreach($output['logs']['console'] as $log) { + echo ' + + '; + if($class == '') $class = 'alt'; + else $class = ''; + } + + echo '
'.$log['type'].''; + if($log['type'] == 'log') { + echo '
'.$log['data'].'
'; + } + elseif($log['type'] == 'memory') { + echo '
'.$log['data'].'
'.$log['dataType'].': '.$log['name'].'
'; + } + elseif($log['type'] == 'speed') { + echo '
'.$log['data'].'
'.$log['name'].'
'; + } + elseif($log['type'] == 'error') { + echo '
Line '.$log['line'].' : '.$log['data'].'
'.$log['file'].'
'; + } + + echo '
'; } echo '
'; @@ -212,28 +212,28 @@ function addEvent( obj, type, fn ) { echo '
'; if($output['logs']['speedCount'] == 0) { - echo '

This panel has no log items.

'; + echo '

This panel has no log items.

'; } else { - echo ' - - -
'.$output['speedTotals']['total'].'

Load Time

'.$output['speedTotals']['allowed'].'

Max Execution Time

- '; - - $class = ''; - foreach($output['logs']['console'] as $log) { - if($log['type'] == 'speed') { - echo ' - '; - if($class == '') $class = 'alt'; - else $class = ''; - } - } - - echo '
'; - echo '
'.$log['data'].'
'.$log['name'].'
'; - echo '
'; + echo ' + + +
'.$output['speedTotals']['total'].'

Load Time

'.$output['speedTotals']['allowed'].'

Max Execution Time

+ '; + + $class = ''; + foreach($output['logs']['console'] as $log) { + if($log['type'] == 'speed') { + echo ' + '; + if($class == '') $class = 'alt'; + else $class = ''; + } + } + + echo '
'; + echo '
'.$log['data'].'
'.$log['name'].'
'; + echo '
'; } echo '
'; @@ -241,35 +241,35 @@ function addEvent( obj, type, fn ) { echo '
'; if($output['queryTotals']['count'] == 0) { - echo '

This panel has no log items.

'; + echo '

This panel has no log items.

'; } else { - echo ' - - - -
'.$output['queryTotals']['count'].'

Total Queries

'.$output['queryTotals']['time'].'

Total Time

0

Duplicates

- '; - - $class = ''; - foreach($output['queries'] as $query) { - echo ' - '; - if($class == '') $class = 'alt'; - else $class = ''; - } - - echo '
'.$query['sql']; - if($query['explain']) { - echo ' - Possible keys: '.$query['explain']['possible_keys'].' · - Key Used: '.$query['explain']['key'].' · - Type: '.$query['explain']['type'].' · - Rows: '.$query['explain']['rows'].' · - Speed: '.$query['time'].' - '; - } - echo '
'; + echo ' + + + +
'.$output['queryTotals']['count'].'

Total Queries

'.$output['queryTotals']['time'].'

Total Time

0

Duplicates

+ '; + + $class = ''; + foreach($output['queries'] as $query) { + echo ' + '; + if($class == '') $class = 'alt'; + else $class = ''; + } + + echo '
'.$query['sql']; + if($query['explain']) { + echo ' + Possible keys: '.$query['explain']['possible_keys'].' · + Key Used: '.$query['explain']['key'].' · + Type: '.$query['explain']['type'].' · + Rows: '.$query['explain']['rows'].' · + Speed: '.$query['time'].' + '; + } + echo '
'; } echo '
'; @@ -277,27 +277,27 @@ function addEvent( obj, type, fn ) { echo '
'; if($output['logs']['memoryCount'] == 0) { - echo '

This panel has no log items.

'; + echo '

This panel has no log items.

'; } else { - echo ' - - -
'.$output['memoryTotals']['used'].'

Used Memory

'.$output['memoryTotals']['total'].'

Total Available

- '; - - $class = ''; - foreach($output['logs']['console'] as $log) { - if($log['type'] == 'memory') { - echo ''; - echo ''; - echo ''; - if($class == '') $class = 'alt'; - else $class = ''; - } - } - - echo '
'.$log['data'].' '.$log['dataType'].': '.$log['name'].'
'; + echo ' + + +
'.$output['memoryTotals']['used'].'

Used Memory

'.$output['memoryTotals']['total'].'

Total Available

+ '; + + $class = ''; + foreach($output['logs']['console'] as $log) { + if($log['type'] == 'memory') { + echo ''; + echo ''; + echo ''; + if($class == '') $class = 'alt'; + else $class = ''; + } + } + + echo '
'.$log['data'].' '.$log['dataType'].': '.$log['name'].'
'; } echo '
'; @@ -305,44 +305,44 @@ function addEvent( obj, type, fn ) { echo '
'; if($output['fileTotals']['count'] == 0) { - echo '

This panel has no log items.

'; + echo '

This panel has no log items.

'; } else { - echo ' - - - -
'.$output['fileTotals']['count'].'

Total Files

'.$output['fileTotals']['size'].'

Total Size

'.$output['fileTotals']['largest'].'

Largest

- '; - - $class =''; - foreach($output['files'] as $file) { - echo ''; - if($class == '') $class = 'alt'; - else $class = ''; - } - - echo '
'.$file['size'].' '.$file['name'].'
'; + echo ' + + + +
'.$output['fileTotals']['count'].'

Total Files

'.$output['fileTotals']['size'].'

Total Size

'.$output['fileTotals']['largest'].'

Largest

+ '; + + $class =''; + foreach($output['files'] as $file) { + echo ''; + if($class == '') $class = 'alt'; + else $class = ''; + } + + echo '
'.$file['size'].' '.$file['name'].'
'; } echo '
'; echo <<
'; } diff --git a/includes/pqp/index.php b/includes/pqp/index.php index 05da7fca4..d3396e918 100644 --- a/includes/pqp/index.php +++ b/includes/pqp/index.php @@ -19,94 +19,94 @@ //require_once('classes/MySqlDatabase.php'); class PQPExample { - - private $profiler; - private $db = ''; - - public function __construct() { - $this->profiler = new PhpQuickProfiler(PhpQuickProfiler::getMicroTime()); - } - - public function init() { - $this->sampleConsoleData(); - $this->sampleDatabaseData(); - $this->sampleMemoryLeak(); - $this->sampleSpeedComparison(); - } - - /*------------------------------------------- - EXAMPLES OF THE 4 CONSOLE FUNCTIONS - -------------------------------------------*/ - - public function sampleConsoleData() { - try { - Console::log('Begin logging data'); - Console::logMemory($this, 'PQP Example Class : Line '.__LINE__); - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::log(array('Name' => 'Ryan', 'Last' => 'Campbell')); - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::logMemory($this, 'PQP Example Class : Line '.__LINE__); - Console::log('Ending log below with a sample error.'); - throw new Exception('Unable to write to log!'); - } - catch(Exception $e) { - Console::logError($e, 'Sample error logging.'); - } - } - - /*------------------------------------- - DATABASE OBJECT TO LOG QUERIES - --------------------------------------*/ - - public function sampleDatabaseData() { - /*$this->db = new MySqlDatabase( - 'your DB host', - 'your DB user', - 'your DB password'); - $this->db->connect(true); - $this->db->changeDatabase('your db name'); - - $sql = 'SELECT PostId FROM Posts WHERE PostId > 2'; - $rs = $this->db->query($sql); - - $sql = 'SELECT COUNT(PostId) FROM Posts'; - $rs = $this->db->query($sql); - - $sql = 'SELECT COUNT(PostId) FROM Posts WHERE PostId != 1'; - $rs = $this->db->query($sql);*/ - } - - /*----------------------------------- - EXAMPLE MEMORY LEAK DETECTED - ------------------------------------*/ - - public function sampleMemoryLeak() { - $ret = ''; - $longString = 'This is a really long string that when appended with the . symbol - will cause memory to be duplicated in order to create the new string.'; - for($i = 0; $i < 10; $i++) { - $ret = $ret . $longString; - Console::logMemory($ret, 'Watch memory leak -- iteration '.$i); - } - } - - /*----------------------------------- - POINT IN TIME SPEED MARKS - ------------------------------------*/ - - public function sampleSpeedComparison() { - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::logSpeed('Time taken to get to line '.__LINE__); - Console::logSpeed('Time taken to get to line '.__LINE__); - } - - public function __destruct() { - $this->profiler->display($this->db); - } - + + private $profiler; + private $db = ''; + + public function __construct() { + $this->profiler = new PhpQuickProfiler(PhpQuickProfiler::getMicroTime()); + } + + public function init() { + $this->sampleConsoleData(); + $this->sampleDatabaseData(); + $this->sampleMemoryLeak(); + $this->sampleSpeedComparison(); + } + + /*------------------------------------------- + EXAMPLES OF THE 4 CONSOLE FUNCTIONS + -------------------------------------------*/ + + public function sampleConsoleData() { + try { + Console::log('Begin logging data'); + Console::logMemory($this, 'PQP Example Class : Line '.__LINE__); + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::log(array('Name' => 'Ryan', 'Last' => 'Campbell')); + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::logMemory($this, 'PQP Example Class : Line '.__LINE__); + Console::log('Ending log below with a sample error.'); + throw new Exception('Unable to write to log!'); + } + catch(Exception $e) { + Console::logError($e, 'Sample error logging.'); + } + } + + /*------------------------------------- + DATABASE OBJECT TO LOG QUERIES + --------------------------------------*/ + + public function sampleDatabaseData() { + /*$this->db = new MySqlDatabase( + 'your DB host', + 'your DB user', + 'your DB password'); + $this->db->connect(true); + $this->db->changeDatabase('your db name'); + + $sql = 'SELECT PostId FROM Posts WHERE PostId > 2'; + $rs = $this->db->query($sql); + + $sql = 'SELECT COUNT(PostId) FROM Posts'; + $rs = $this->db->query($sql); + + $sql = 'SELECT COUNT(PostId) FROM Posts WHERE PostId != 1'; + $rs = $this->db->query($sql);*/ + } + + /*----------------------------------- + EXAMPLE MEMORY LEAK DETECTED + ------------------------------------*/ + + public function sampleMemoryLeak() { + $ret = ''; + $longString = 'This is a really long string that when appended with the . symbol + will cause memory to be duplicated in order to create the new string.'; + for($i = 0; $i < 10; $i++) { + $ret = $ret . $longString; + Console::logMemory($ret, 'Watch memory leak -- iteration '.$i); + } + } + + /*----------------------------------- + POINT IN TIME SPEED MARKS + ------------------------------------*/ + + public function sampleSpeedComparison() { + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::logSpeed('Time taken to get to line '.__LINE__); + Console::logSpeed('Time taken to get to line '.__LINE__); + } + + public function __destruct() { + $this->profiler->display($this->db); + } + } $pqp = new PQPExample(); @@ -128,50 +128,50 @@ public function __destruct() {
-

On this Page You Can See How to
Use the PHP Quick Profiler to...

- -
    -
  • Log PHP Objects. [ Demo ]
  • -
  • Watch as a string eats up memory. [ Demo ]
  • -
  • Monitor our queries and their indexes. [ Demo ]
  • -
  • Ensure page execution time is acceptable. [ Demo ]
  • -
  • Prevent files from getting out of control. [ Demo ]
  • -
- - Return to Particletree. +

On this Page You Can See How to
Use the PHP Quick Profiler to...

+ +
    +
  • Log PHP Objects. [ Demo ]
  • +
  • Watch as a string eats up memory. [ Demo ]
  • +
  • Monitor our queries and their indexes. [ Demo ]
  • +
  • Ensure page execution time is acceptable. [ Demo ]
  • +
  • Prevent files from getting out of control. [ Demo ]
  • +
+ + Return to Particletree.
diff --git a/includes/pqp/pqp.tpl b/includes/pqp/pqp.tpl index 699b4f684..15fa86aa4 100644 --- a/includes/pqp/pqp.tpl +++ b/includes/pqp/pqp.tpl @@ -1,271 +1,271 @@ {literal} {/literal} \ No newline at end of file diff --git a/includes/template_class.php b/includes/template_class.php index 87a54fb2a..8e72d41ed 100644 --- a/includes/template_class.php +++ b/includes/template_class.php @@ -1,200 +1,200 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class Template { - - /** - * Template files directory - * - * @var string - */ - var $template_dir; - - /** - * Template Variables - * - * @var array - */ - var $vars = array(); - - /** - * Template file - * - * @var string - */ - var $file; - - /** - * Constructor - * - * @access public - */ - function __construct() { - - } - - /** - * Set the template file - * - * @param string $file - */ - function set_template($file = null) { - $this->file = $this->template_dir.$file; - return; - } - - /** - * Set a template variable - * - * @param string $name - * @param unknown_value $value - * @access public - */ - function set($name, $value) { - - if (is_object($value)) { - $class = 'Template'; - if ($value instanceof $this) { - $value = $value->fetch(); - } - } - - $this->vars[$name] = $value; - return; - } - - /** - * Open, parse, and return the template file. - * - * @param string $file - * @return string $contents - * @access public - */ - function fetch($file = null) { - if(!$file): - $file = $this->file; - else: - $file = $this->template_dir.$file; - endif; - - extract($this->vars); // Extract the vars to local namespace - ob_start(); // Start output buffering - include($file); // Include the file - $contents = ob_get_contents(); // Get the contents of the buffer - ob_end_clean(); // End buffering and discard - return $contents; // Return the contents - } - -} - -/** -* An extension to Template that provides automatic caching of -* template contents. -*/ -class CachedTemplate extends Template { - var $cache_id; - var $expire; - var $cached; - - /** - * Constructor. - * - * @param $cache_id string unique cache identifier - * @param $expire int number of seconds the cache will live - */ - function __construct($cache_id = null, $expire = 900) { - parent::__construct(); - $this->cache_id = $cache_id ? 'cache/' . md5($cache_id) : $cache_id; - $this->expire = $expire; - } - - /** - * Test to see whether the currently loaded cache_id has a valid - * corrosponding cache file. - */ - function is_cached() { - if($this->cached) return true; - - // Passed a cache_id? - if(!$this->cache_id) return false; - - // Cache file exists? - if(!file_exists($this->cache_id)) return false; - - // Can get the time of the file? - if(!($mtime = filemtime($this->cache_id))) return false; - - // Cache expired? - if(($mtime + $this->expire) < time()) { - @unlink($this->cache_id); - return false; - } - else { - /** - * Cache the results of this is_cached() call. Why? So - * we don't have to double the overhead for each template. - * If we didn't cache, it would be hitting the file system - * twice as much (file_exists() & filemtime() [twice each]). - */ - $this->cached = true; - return true; - } - } - - /** - * This function returns a cached copy of a template (if it exists), - * otherwise, it parses it as normal and caches the content. - * - * @param $file string the template file - */ - function fetch_cache($file) { - if($this->is_cached()) { - $fp = @fopen($this->cache_id, 'r'); - $contents = fread($fp, filesize($this->cache_id)); - fclose($fp); - return $contents; - } - else { - $contents = $this->fetch($file); - - // Write the cache - if($fp = @fopen($this->cache_id, 'w')) { - fwrite($fp, $contents); - fclose($fp); - } - else { - die('Unable to write cache.'); - } - - return $contents; - } - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class Template { + + /** + * Template files directory + * + * @var string + */ + var $template_dir; + + /** + * Template Variables + * + * @var array + */ + var $vars = array(); + + /** + * Template file + * + * @var string + */ + var $file; + + /** + * Constructor + * + * @access public + */ + function __construct() { + + } + + /** + * Set the template file + * + * @param string $file + */ + function set_template($file = null) { + $this->file = $this->template_dir.$file; + return; + } + + /** + * Set a template variable + * + * @param string $name + * @param unknown_value $value + * @access public + */ + function set($name, $value) { + + if (is_object($value)) { + $class = 'Template'; + if ($value instanceof $this) { + $value = $value->fetch(); + } + } + + $this->vars[$name] = $value; + return; + } + + /** + * Open, parse, and return the template file. + * + * @param string $file + * @return string $contents + * @access public + */ + function fetch($file = null) { + if(!$file): + $file = $this->file; + else: + $file = $this->template_dir.$file; + endif; + + extract($this->vars); // Extract the vars to local namespace + ob_start(); // Start output buffering + include($file); // Include the file + $contents = ob_get_contents(); // Get the contents of the buffer + ob_end_clean(); // End buffering and discard + return $contents; // Return the contents + } + +} + +/** +* An extension to Template that provides automatic caching of +* template contents. +*/ +class CachedTemplate extends Template { + var $cache_id; + var $expire; + var $cached; + + /** + * Constructor. + * + * @param $cache_id string unique cache identifier + * @param $expire int number of seconds the cache will live + */ + function __construct($cache_id = null, $expire = 900) { + parent::__construct(); + $this->cache_id = $cache_id ? 'cache/' . md5($cache_id) : $cache_id; + $this->expire = $expire; + } + + /** + * Test to see whether the currently loaded cache_id has a valid + * corrosponding cache file. + */ + function is_cached() { + if($this->cached) return true; + + // Passed a cache_id? + if(!$this->cache_id) return false; + + // Cache file exists? + if(!file_exists($this->cache_id)) return false; + + // Can get the time of the file? + if(!($mtime = filemtime($this->cache_id))) return false; + + // Cache expired? + if(($mtime + $this->expire) < time()) { + @unlink($this->cache_id); + return false; + } + else { + /** + * Cache the results of this is_cached() call. Why? So + * we don't have to double the overhead for each template. + * If we didn't cache, it would be hitting the file system + * twice as much (file_exists() & filemtime() [twice each]). + */ + $this->cached = true; + return true; + } + } + + /** + * This function returns a cached copy of a template (if it exists), + * otherwise, it parses it as normal and caches the content. + * + * @param $file string the template file + */ + function fetch_cache($file) { + if($this->is_cached()) { + $fp = @fopen($this->cache_id, 'r'); + $contents = fread($fp, filesize($this->cache_id)); + fclose($fp); + return $contents; + } + else { + $contents = $this->fetch($file); + + // Write the cache + if($fp = @fopen($this->cache_id, 'w')) { + fwrite($fp, $contents); + fclose($fp); + } + else { + die('Unable to write cache.'); + } + + return $contents; + } + } +} + ?> \ No newline at end of file diff --git a/index.php b/index.php index 8395d0bdf..a65ec29b4 100644 --- a/index.php +++ b/index.php @@ -27,8 +27,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ // Initialize owa admin @@ -36,18 +36,18 @@ if (!$owa->isOwaInstalled()) { - // redirect to install - owa_lib::redirectBrowser(owa_coreAPI::getSetting('base','public_url').'install.php'); + // redirect to install + owa_lib::redirectBrowser(owa_coreAPI::getSetting('base','public_url').'install.php'); } if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - // run controller or view and echo page content - echo $owa->handleRequestFromURL(); + // run controller or view and echo page content + echo $owa->handleRequestFromURL(); } else { - - // unload owa - $owa->restInPeace(); + + // unload owa + $owa->restInPeace(); } ?> \ No newline at end of file diff --git a/ini_db.php b/ini_db.php index 4e37f035c..17c28f21d 100644 --- a/ini_db.php +++ b/ini_db.php @@ -1,236 +1,236 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category wa - * @package wa - * @version $Revision$ - * @since wa 1.0.0 - */ -class ini_db extends owa_base { - - /** - * Data file - * - * @var unknown_type - */ - var $ini_file; - - /** - * Result Format - * - * @var string - */ - var $return_format; - - /** - * Cache flag - * - * @var boolean - */ - var $cache = true; - - - /** - * Database Access Object - * - * @var object - */ - var $db; - - /** - * Constructor - * - * @param string $ini_file - * @param string_type $sections - * @param string $return_format - * @access public - * @return ini_db - */ - function __construct($ini_file, $sections = null, $return_format = 'object') { - - parent::__construct(); - $this->ini_file = $ini_file; - $this->return_format = $return_format; - - if (!empty($sections)){ - $this->db = $this->readINIfile($this->ini_file, ';'); - } else { - $this->db = file($this->ini_file); - } - } - - /** - * Returns a section from an ini file based on regex match rule - * contained as keys in an ini file. - * - * @param string - * @access public - */ - function fetch($haystack) { - - $record = null; - - foreach ($this->db as $key=>$value) { - if (($key!='#*#')&&(!array_key_exists('parent',$value))) continue; - - $keyEreg = '#'.$key.'#'; - - if (preg_match($keyEreg, $haystack)) { - $record=array('regex'=>strtolower($keyEreg),'pattern'=>$key)+$value; - - $maxDeep=8; - while (array_key_exists('parent',$value)&&(--$maxDeep>0)) - - $record+=($value = $this->db[strtolower($value['parent'])]); - break; - } - } - - switch ($this->return_format) { - case "array": - return $record; - break; - case "object": - return ((object)$record); - break; - } - return $record; - } - - /** - * Returns part of the passed string based on regex match rules - * contained as keys in an ini file. - * - * @param string - * @access public - * @return string - */ - function match($haystack) { - - $needle = ''; - - if (!empty($haystack)): - - $tmp = ''; - - foreach ($this->db as $key => $value) { - - if (!empty($value)): - //$this->e->debug('ref db:'.print_r($this->db, true)); - preg_match(trim($value), $haystack, $tmp); - if (!empty($tmp)): - $needle = $tmp; - //$this->e->debug('ref db:'.print_r($tmp, true)); - endif; - endif; - } - - return $needle; - - else: - return; - endif; - } - - function contains($haystack = '') { - - $pos = false; - - if ($haystack) { - - foreach ($this->db as $k => $needle) { - $needle = substr(strtolower(trim($needle)),1,-1); - $pos = strpos(strtolower($haystack), $needle); - - if ($pos) { - owa_coreAPI::debug(sprintf('Haystack contains "%s" at position %d', $needle, $pos)); - return true; - } - } - - return false; - } - } - - /** - * Fetch a record set and perfrom a regex replace on the name - * - * @param string $haystack - * @return string - */ - function fetch_replace($haystack) { - - $record = $this->fetch($haystack); - - //print_r($record); - - $new_record = preg_replace($record->regex, $record->name, $haystack); - - return $new_record; - } - - /** - * Reads INI file - * - * @param string $filename - * @param string $commentchar - * @return array - */ - function readINIfile ($filename, $commentchar) { - $array1 = file($filename); - $section = ''; - foreach ($array1 as $filedata) { - $dataline = trim($filedata); - $firstchar = substr($dataline, 0, 1); - if ($firstchar!=$commentchar && $dataline!='') { - //It's an entry (not a comment and not a blank line) - if ($firstchar == '[' && substr($dataline, -1, 1) == ']') { - //It's a section - $section = strtolower(substr($dataline, 1, -1)); - } else { - //It's a key... - $delimiter = strpos($dataline, '='); - if ($delimiter > 0) { - //...with a value - $key = strtolower(trim(substr($dataline, 0, $delimiter))); - $value = trim(substr($dataline, $delimiter + 1)); - if (substr($value, 1, 1) == '"' && substr($value, -1, 1) == '"') { $value = substr($value, 1, -1); } - $array2[$section][$key] = stripcslashes($value); - } else { - //...without a value - $array2[$section][strtolower(trim($dataline))]=''; - } - } - } else { - //It's a comment or blank line. Ignore. - } - } - - return $array2; - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category wa + * @package wa + * @version $Revision$ + * @since wa 1.0.0 + */ +class ini_db extends owa_base { + + /** + * Data file + * + * @var unknown_type + */ + var $ini_file; + + /** + * Result Format + * + * @var string + */ + var $return_format; + + /** + * Cache flag + * + * @var boolean + */ + var $cache = true; + + + /** + * Database Access Object + * + * @var object + */ + var $db; + + /** + * Constructor + * + * @param string $ini_file + * @param string_type $sections + * @param string $return_format + * @access public + * @return ini_db + */ + function __construct($ini_file, $sections = null, $return_format = 'object') { + + parent::__construct(); + $this->ini_file = $ini_file; + $this->return_format = $return_format; + + if (!empty($sections)){ + $this->db = $this->readINIfile($this->ini_file, ';'); + } else { + $this->db = file($this->ini_file); + } + } + + /** + * Returns a section from an ini file based on regex match rule + * contained as keys in an ini file. + * + * @param string + * @access public + */ + function fetch($haystack) { + + $record = null; + + foreach ($this->db as $key=>$value) { + if (($key!='#*#')&&(!array_key_exists('parent',$value))) continue; + + $keyEreg = '#'.$key.'#'; + + if (preg_match($keyEreg, $haystack)) { + $record=array('regex'=>strtolower($keyEreg),'pattern'=>$key)+$value; + + $maxDeep=8; + while (array_key_exists('parent',$value)&&(--$maxDeep>0)) + + $record+=($value = $this->db[strtolower($value['parent'])]); + break; + } + } + + switch ($this->return_format) { + case "array": + return $record; + break; + case "object": + return ((object)$record); + break; + } + return $record; + } + + /** + * Returns part of the passed string based on regex match rules + * contained as keys in an ini file. + * + * @param string + * @access public + * @return string + */ + function match($haystack) { + + $needle = ''; + + if (!empty($haystack)): + + $tmp = ''; + + foreach ($this->db as $key => $value) { + + if (!empty($value)): + //$this->e->debug('ref db:'.print_r($this->db, true)); + preg_match(trim($value), $haystack, $tmp); + if (!empty($tmp)): + $needle = $tmp; + //$this->e->debug('ref db:'.print_r($tmp, true)); + endif; + endif; + } + + return $needle; + + else: + return; + endif; + } + + function contains($haystack = '') { + + $pos = false; + + if ($haystack) { + + foreach ($this->db as $k => $needle) { + $needle = substr(strtolower(trim($needle)),1,-1); + $pos = strpos(strtolower($haystack), $needle); + + if ($pos) { + owa_coreAPI::debug(sprintf('Haystack contains "%s" at position %d', $needle, $pos)); + return true; + } + } + + return false; + } + } + + /** + * Fetch a record set and perfrom a regex replace on the name + * + * @param string $haystack + * @return string + */ + function fetch_replace($haystack) { + + $record = $this->fetch($haystack); + + //print_r($record); + + $new_record = preg_replace($record->regex, $record->name, $haystack); + + return $new_record; + } + + /** + * Reads INI file + * + * @param string $filename + * @param string $commentchar + * @return array + */ + function readINIfile ($filename, $commentchar) { + $array1 = file($filename); + $section = ''; + foreach ($array1 as $filedata) { + $dataline = trim($filedata); + $firstchar = substr($dataline, 0, 1); + if ($firstchar!=$commentchar && $dataline!='') { + //It's an entry (not a comment and not a blank line) + if ($firstchar == '[' && substr($dataline, -1, 1) == ']') { + //It's a section + $section = strtolower(substr($dataline, 1, -1)); + } else { + //It's a key... + $delimiter = strpos($dataline, '='); + if ($delimiter > 0) { + //...with a value + $key = strtolower(trim(substr($dataline, 0, $delimiter))); + $value = trim(substr($dataline, $delimiter + 1)); + if (substr($value, 1, 1) == '"' && substr($value, -1, 1) == '"') { $value = substr($value, 1, -1); } + $array2[$section][$key] = stripcslashes($value); + } else { + //...without a value + $array2[$section][strtolower(trim($dataline))]=''; + } + } + } else { + //It's a comment or blank line. Ignore. + } + } + + return $array2; + } +} + ?> \ No newline at end of file diff --git a/install.php b/install.php index fb55640fc..1698e2a14 100644 --- a/install.php +++ b/install.php @@ -1,59 +1,59 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -// Initialize owa -//define('OWA_ERROR_HANDLER', 'development'); -define('OWA_CACHE_OBJECTS', false); -define('OWA_INSTALLING', true); -$owa = new owa_php(); -if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - - // need third param here so that seting is not persisted. - $owa->setSetting('base','main_url', 'install.php'); - // run controller, echo page content - $do = owa_coreAPI::getRequestParam('do'); - $params = array(); - if (empty($do)) { - - $params['do'] = 'base.installStart'; - } - - // run controller or view and echo page content - echo $owa->handleRequest($params); - -} else { - // unload owa - $owa->restInPeace(); -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +// Initialize owa +//define('OWA_ERROR_HANDLER', 'development'); +define('OWA_CACHE_OBJECTS', false); +define('OWA_INSTALLING', true); +$owa = new owa_php(); +if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { + + // need third param here so that seting is not persisted. + $owa->setSetting('base','main_url', 'install.php'); + // run controller, echo page content + $do = owa_coreAPI::getRequestParam('do'); + $params = array(); + if (empty($do)) { + + $params['do'] = 'base.installStart'; + } + + // run controller or view and echo page content + echo $owa->handleRequest($params); + +} else { + // unload owa + $owa->restInPeace(); +} + ?> \ No newline at end of file diff --git a/log.php b/log.php index 4ace21669..890b32b1f 100644 --- a/log.php +++ b/log.php @@ -1,100 +1,100 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -ignore_user_abort(true); - -// turn off gzip compression -if ( function_exists( 'apache_setenv' ) ) { - apache_setenv( 'no-gzip', 1 ); -} - -ini_set('zlib.output_compression', 0); - -// turn on output buffering if necessary -if (ob_get_level() == 0) { - ob_start(); -} - -// removing any content encoding like gzip etc. -header('Content-encoding: none', true); - -//check to se if request is a POST -if ($_SERVER['REQUEST_METHOD'] === 'POST') { - - // redirect to blank.php - owa_lib::redirectBrowser( str_replace('log.php', 'blank.php', owa_lib::get_current_url() ) ); - // necessary or else buffer is not actually flushed - echo ' '; -} else { - // return 1x1 pixel gif - header("Content-type: image/gif"); - // needed to avoid cache time on browser side - header("Content-Length: 42"); - header("Cache-Control: private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); - header("Expires: Wed, 11 Jan 2000 12:59:00 GMT"); - header("Last-Modified: Wed, 11 Jan 2006 12:59:00 GMT"); - header("Pragma: no-cache"); - - echo sprintf( - '%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%', - 71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59 - ); -} - -// flush all output buffers. No reason to make the user wait for OWA. -ob_flush(); -flush(); -ob_end_flush(); - -// Create instance of OWA -require_once(OWA_BASE_DIR.'/owa_php.php'); -$config = array( - - 'tracking_mode' => true -); - -$owa = new owa_php( $config ); - -// check to see if this endpoint is enabled. -if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - - $owa->e->debug('Logging new tracking event from request.'); - $owa->logEventFromUrl(); - -} else { - // unload owa - $owa->restInPeace(); -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +ignore_user_abort(true); + +// turn off gzip compression +if ( function_exists( 'apache_setenv' ) ) { + apache_setenv( 'no-gzip', 1 ); +} + +ini_set('zlib.output_compression', 0); + +// turn on output buffering if necessary +if (ob_get_level() == 0) { + ob_start(); +} + +// removing any content encoding like gzip etc. +header('Content-encoding: none', true); + +//check to se if request is a POST +if ($_SERVER['REQUEST_METHOD'] === 'POST') { + + // redirect to blank.php + owa_lib::redirectBrowser( str_replace('log.php', 'blank.php', owa_lib::get_current_url() ) ); + // necessary or else buffer is not actually flushed + echo ' '; +} else { + // return 1x1 pixel gif + header("Content-type: image/gif"); + // needed to avoid cache time on browser side + header("Content-Length: 42"); + header("Cache-Control: private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); + header("Expires: Wed, 11 Jan 2000 12:59:00 GMT"); + header("Last-Modified: Wed, 11 Jan 2006 12:59:00 GMT"); + header("Pragma: no-cache"); + + echo sprintf( + '%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%', + 71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59 + ); +} + +// flush all output buffers. No reason to make the user wait for OWA. +ob_flush(); +flush(); +ob_end_flush(); + +// Create instance of OWA +require_once(OWA_BASE_DIR.'/owa_php.php'); +$config = array( + + 'tracking_mode' => true +); + +$owa = new owa_php( $config ); + +// check to see if this endpoint is enabled. +if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { + + $owa->e->debug('Logging new tracking event from request.'); + $owa->logEventFromUrl(); + +} else { + // unload owa + $owa->restInPeace(); +} + ?> \ No newline at end of file diff --git a/modules/base/apiRequest.php b/modules/base/apiRequest.php index 976a4776c..dee7d000a 100644 --- a/modules/base/apiRequest.php +++ b/modules/base/apiRequest.php @@ -27,93 +27,93 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 + * @version $Revision$ + * @since owa 1.3.0 */ class owa_apiRequestController extends owa_controller { - - function __construct($params) { - - return parent::__construct($params); - } - - function getRequiredCapability() { - - $s = owa_coreAPI::serviceSingleton(); - // lookup method class - $do = $s->getApiMethodClass($this->getParam('do')); - - if ($do) { - - // check for capability - if (array_key_exists('required_capability', $do)) { - return $do['required_capability']; - } - } - } - - function doAction() { - - - /* CHECK USER FOR CAPABILITIES */ - if ( ! $this->checkCapabilityAndAuthenticateUser( $this->getRequiredCapability() ) ) { - - return $this->data; - } - - /* PERFORM PRE ACTION */ - // often used by abstract descendant controllers to set various things - $this->pre(); - /* PERFORM MAIN ACTION */ - return $this->finishActionCall($this->action()); - } - - function action() { - - //determine output format, json is default. - $format = $this->getParam('format'); - - if ( ! $format ) { - - $format = 'json'; - } - - // set content type of reponse - owa_lib::setContentTypeHeader($format); - - $map = owa_coreAPI::getRequest()->getAllOwaParams(); - $output = owa_coreAPI::executeApiCommand($map); - - // assign to a view for output - if ( $format === 'json' || $format === 'jsonp') { - - $this->setView( 'base.json' ); - $this->set( 'json', $output ); - $this->set( 'format', $format ); - - if ( $format ==='jsonp' ) { - - $this->set('jsonpCallback', $this->getParam('jsonpCallback') ); - } - - } else { - //@todo move this to a generic raw output view. - echo $output; - } - - } - - function notAuthenticatedAction() { - - $this->setErrorMsg('Authentication failed.'); - $this->setView('base.apiError'); - } - - function authenticatedButNotCapableAction($additionalMessage = '') { - $this->setErrorMsg('Thus user is not capable to perform this api method.'); - $this->setView('base.apiError'); - } + + function __construct($params) { + + return parent::__construct($params); + } + + function getRequiredCapability() { + + $s = owa_coreAPI::serviceSingleton(); + // lookup method class + $do = $s->getApiMethodClass($this->getParam('do')); + + if ($do) { + + // check for capability + if (array_key_exists('required_capability', $do)) { + return $do['required_capability']; + } + } + } + + function doAction() { + + + /* CHECK USER FOR CAPABILITIES */ + if ( ! $this->checkCapabilityAndAuthenticateUser( $this->getRequiredCapability() ) ) { + + return $this->data; + } + + /* PERFORM PRE ACTION */ + // often used by abstract descendant controllers to set various things + $this->pre(); + /* PERFORM MAIN ACTION */ + return $this->finishActionCall($this->action()); + } + + function action() { + + //determine output format, json is default. + $format = $this->getParam('format'); + + if ( ! $format ) { + + $format = 'json'; + } + + // set content type of reponse + owa_lib::setContentTypeHeader($format); + + $map = owa_coreAPI::getRequest()->getAllOwaParams(); + $output = owa_coreAPI::executeApiCommand($map); + + // assign to a view for output + if ( $format === 'json' || $format === 'jsonp') { + + $this->setView( 'base.json' ); + $this->set( 'json', $output ); + $this->set( 'format', $format ); + + if ( $format ==='jsonp' ) { + + $this->set('jsonpCallback', $this->getParam('jsonpCallback') ); + } + + } else { + //@todo move this to a generic raw output view. + echo $output; + } + + } + + function notAuthenticatedAction() { + + $this->setErrorMsg('Authentication failed.'); + $this->setView('base.apiError'); + } + + function authenticatedButNotCapableAction($additionalMessage = '') { + $this->setErrorMsg('Thus user is not capable to perform this api method.'); + $this->setView('base.apiError'); + } } /** @@ -124,18 +124,18 @@ function authenticatedButNotCapableAction($additionalMessage = '') { * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.5.0 + * @version $Revision$ + * @since owa 1.5.0 */ class owa_apiErrorView extends owa_view { - function render() { - - $this->t->set_template('wrapper_blank.tpl'); - $this->body->set_template('apiError.php'); - $this->body->set( 'error_msg', $this->get( 'error_msg' ) ); - } + function render() { + + $this->t->set_template('wrapper_blank.tpl'); + $this->body->set_template('apiError.php'); + $this->body->set( 'error_msg', $this->get( 'error_msg' ) ); + } } ?> \ No newline at end of file diff --git a/modules/base/build.php b/modules/base/build.php index 6bb516910..a4c5dba03 100644 --- a/modules/base/build.php +++ b/modules/base/build.php @@ -1,90 +1,90 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_buildController extends owa_cliController { - - function __construct($params) { - - parent::__construct($params); - - $this->setRequiredCapability('edit_modules'); - } - - function action() { - - $packages = owa_coreAPI::getBuildPackages(); - - if ( $this->getParam('package') ) { - - $packages = array($packages[$this->getParam('package')]); - } - - if ($packages) { - foreach ($packages as $package) { - - owa_coreAPI::debug(sprintf("Building %s Package.", $package['name'] ) ); - $con = sprintf("/* OWA %s package file created %s */ \n\n", $package['name'] ,date( DATE_RFC822 ) ); - $isMin = false; - foreach ($package['files'] as $name => $file_info) { - - owa_coreAPI::debug("Reading file from: " . $file_info['path'] ); - $con .= "/* Start of $name */ \n\n"; - $content = file_get_contents( $file_info['path'] ); - if (isset($file_info['compression']) && $file_info['compression'] === 'minify') { - owa_coreAPI::debug("Minimizing Javascript in: " . $file_info['path'] ); - $content = JSMin::minify($content); - $isMin = true; - } - $con .= $content . "\n\n"; - $con .= "/* End of $name */ \n\n"; - } - $file_name = $package['output_dir'].$package['name']."-combined"; - if ($isMin) { - $file_name .= '-min'; - } - - $file_name .= '.' . $package['type']; - - owa_coreAPI::debug('Writing package to file: '.$file_name); - $handle = fopen($file_name, "w"); - fwrite($handle, $con); - fclose($handle); - } - } else { - owa_coreAPI::debug( "No packages registered to build." ); - } - } -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_buildController extends owa_cliController { + + function __construct($params) { + + parent::__construct($params); + + $this->setRequiredCapability('edit_modules'); + } + + function action() { + + $packages = owa_coreAPI::getBuildPackages(); + + if ( $this->getParam('package') ) { + + $packages = array($packages[$this->getParam('package')]); + } + + if ($packages) { + foreach ($packages as $package) { + + owa_coreAPI::debug(sprintf("Building %s Package.", $package['name'] ) ); + $con = sprintf("/* OWA %s package file created %s */ \n\n", $package['name'] ,date( DATE_RFC822 ) ); + $isMin = false; + foreach ($package['files'] as $name => $file_info) { + + owa_coreAPI::debug("Reading file from: " . $file_info['path'] ); + $con .= "/* Start of $name */ \n\n"; + $content = file_get_contents( $file_info['path'] ); + if (isset($file_info['compression']) && $file_info['compression'] === 'minify') { + owa_coreAPI::debug("Minimizing Javascript in: " . $file_info['path'] ); + $content = JSMin::minify($content); + $isMin = true; + } + $con .= $content . "\n\n"; + $con .= "/* End of $name */ \n\n"; + } + $file_name = $package['output_dir'].$package['name']."-combined"; + if ($isMin) { + $file_name .= '-min'; + } + + $file_name .= '.' . $package['type']; + + owa_coreAPI::debug('Writing package to file: '.$file_name); + $handle = fopen($file_name, "w"); + fwrite($handle, $con); + fclose($handle); + } + } else { + owa_coreAPI::debug( "No packages registered to build." ); + } + } +} + + ?> \ No newline at end of file diff --git a/modules/base/changeUserPasswordCli.php b/modules/base/changeUserPasswordCli.php index 29b561751..6bd5d9f14 100644 --- a/modules/base/changeUserPasswordCli.php +++ b/modules/base/changeUserPasswordCli.php @@ -78,13 +78,13 @@ public function action() } owa_coreAPI::notice( "User password update failed." ); - } + } public function errorAction() { $this->setView('base.changeUserPasswordCli'); $this->set('msgs', $this->getParam('validation_errors')); - } + } } require_once(OWA_BASE_DIR.'/owa_view.php'); diff --git a/modules/base/classes/browscap.php b/modules/base/classes/browscap.php index 48f251792..4016e7b41 100644 --- a/modules/base/classes/browscap.php +++ b/modules/base/classes/browscap.php @@ -1,251 +1,251 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_browscap extends owa_base { - - - /** - * main regex file location - * - * @var array - */ - var $browscap_db; - - /** - * Browscap Record for current User agent - * - * @var unknown_type - */ - var $browser; - - /** - * Current user Agent - * - * @var string - */ - var $ua; - var $cache; - var $cacheExpiration; - - function __construct( $ua = '' ) { - - parent::__construct(); - - // set user agent - $this->ua = $ua; - - // init cache - $this->cache = owa_coreAPI::cacheSingleton(); - $this->cacheExpiration = owa_coreAPI::getSetting('base', 'default_cache_expiration_period'); - $this->cache->setCollectionExpirationPeriod('browscap', $this->cacheExpiration); - - //lookup UA - $this->browser = $this->lookup( $this->ua ); - $this->e->debug('Browser Name : '. $this->getUaFamilyVersion() ); - - } - - // DEPRICATED - function robotCheck() { - - return $this->isRobot(); - } - - function lookup( $user_agent ) { - - $cache_obj = null; - - if ( owa_coreAPI::getSetting('base','cache_objects') ) { - - owa_coreAPI::profile( $this, __FUNCTION__, __LINE__ ); - - $cache_obj = $this->cache->get( 'browscap', $this->ua ); - } - - if ( ! $cache_obj ) { - - $custom_db = owa_coreAPI::getSetting('base','ua-regexes'); - - if ( $custom_db ) { - - $parser = Parser::create($custom_db); - - } else { - $parser = Parser::create(); - } - - $cap = $parser->parse( $this->ua ); - - } else { - - $cap = $cache_obj; - } - if ( ! empty( $cap ) ) { - - if ( owa_coreAPI::getSetting('base', 'cache_objects') ) { - - $family = $cap->ua->family; - - if ( $family != 'Default Browser' ) { - - $this->cache->set( 'browscap', $this->ua, $cap, $this->cacheExpiration ); - } - } - } - - return $cap; - } - - function robotRegexCheck() { - - $robots = array( - 'bot', - 'crawl', - 'spider', - 'curl', - 'host', - 'localhost', - 'java', - 'libcurl', - 'libwww', - 'lwp', - 'perl', - 'php', - 'wget', - 'search', - 'slurp', - 'robot' - ); - - $match = false; - - foreach ( $robots as $k => $robot ) { - - $match = strpos( $this->ua, $robot ); - - if ( $match ) { - - owa_coreAPI::debug('Robot detect string found.'); - - break; - } - } - - return $match; - } - - function isRobot() { - - return $this->robotRegexCheck(); - } - - function get( $name ) { - - return $this->browser->$name; - } - - function getUaFamily() { - - return $this->browser->ua->family; - } - - function getUaVersionMajor() { - - return $this->browser->ua->major; - } - - function getUaVersionMinor() { - - return $this->browser->ua->minor; - } - - function getUaVersionPatch() { - - return $this->browser->ua->patch; - } - - function getUaFamilyVersion() { - - return $this->browser->ua->toVersion(); - } - - function getUaVersion() { - - return $this->browser->ua->toVersion(); - } - - function getUaOriginal() { - - return $this->browser->originalUserAgent; - } - - function getUaOs() { - - return $this->browser->toString(); - } - - function getOsFamily() { - - return $this->browser->os->family; - } - - function getOsVersionMajor() { - - return $this->browser->os->major; - } - - function getOsVersionMinor() { - - return $this->browser->os->minor; - } - - function getOsVersionPatch() { - - return $this->browser->os->patch; - } - - function getOsFamilyVersion() { - - return $this->browser->os->toString(); - } - - function getOsVersion() { - - return $this->browser->os->toVersion(); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_browscap extends owa_base { + + + /** + * main regex file location + * + * @var array + */ + var $browscap_db; + + /** + * Browscap Record for current User agent + * + * @var unknown_type + */ + var $browser; + + /** + * Current user Agent + * + * @var string + */ + var $ua; + var $cache; + var $cacheExpiration; + + function __construct( $ua = '' ) { + + parent::__construct(); + + // set user agent + $this->ua = $ua; + + // init cache + $this->cache = owa_coreAPI::cacheSingleton(); + $this->cacheExpiration = owa_coreAPI::getSetting('base', 'default_cache_expiration_period'); + $this->cache->setCollectionExpirationPeriod('browscap', $this->cacheExpiration); + + //lookup UA + $this->browser = $this->lookup( $this->ua ); + $this->e->debug('Browser Name : '. $this->getUaFamilyVersion() ); + + } + + // DEPRICATED + function robotCheck() { + + return $this->isRobot(); + } + + function lookup( $user_agent ) { + + $cache_obj = null; + + if ( owa_coreAPI::getSetting('base','cache_objects') ) { + + owa_coreAPI::profile( $this, __FUNCTION__, __LINE__ ); + + $cache_obj = $this->cache->get( 'browscap', $this->ua ); + } + + if ( ! $cache_obj ) { + + $custom_db = owa_coreAPI::getSetting('base','ua-regexes'); + + if ( $custom_db ) { + + $parser = Parser::create($custom_db); + + } else { + $parser = Parser::create(); + } + + $cap = $parser->parse( $this->ua ); + + } else { + + $cap = $cache_obj; + } + if ( ! empty( $cap ) ) { + + if ( owa_coreAPI::getSetting('base', 'cache_objects') ) { + + $family = $cap->ua->family; + + if ( $family != 'Default Browser' ) { + + $this->cache->set( 'browscap', $this->ua, $cap, $this->cacheExpiration ); + } + } + } + + return $cap; + } + + function robotRegexCheck() { + + $robots = array( + 'bot', + 'crawl', + 'spider', + 'curl', + 'host', + 'localhost', + 'java', + 'libcurl', + 'libwww', + 'lwp', + 'perl', + 'php', + 'wget', + 'search', + 'slurp', + 'robot' + ); + + $match = false; + + foreach ( $robots as $k => $robot ) { + + $match = strpos( $this->ua, $robot ); + + if ( $match ) { + + owa_coreAPI::debug('Robot detect string found.'); + + break; + } + } + + return $match; + } + + function isRobot() { + + return $this->robotRegexCheck(); + } + + function get( $name ) { + + return $this->browser->$name; + } + + function getUaFamily() { + + return $this->browser->ua->family; + } + + function getUaVersionMajor() { + + return $this->browser->ua->major; + } + + function getUaVersionMinor() { + + return $this->browser->ua->minor; + } + + function getUaVersionPatch() { + + return $this->browser->ua->patch; + } + + function getUaFamilyVersion() { + + return $this->browser->ua->toVersion(); + } + + function getUaVersion() { + + return $this->browser->ua->toVersion(); + } + + function getUaOriginal() { + + return $this->browser->originalUserAgent; + } + + function getUaOs() { + + return $this->browser->toString(); + } + + function getOsFamily() { + + return $this->browser->os->family; + } + + function getOsVersionMajor() { + + return $this->browser->os->major; + } + + function getOsVersionMinor() { + + return $this->browser->os->minor; + } + + function getOsVersionPatch() { + + return $this->browser->os->patch; + } + + function getOsFamilyVersion() { + + return $this->browser->os->toString(); + } + + function getOsVersion() { + + return $this->browser->os->toVersion(); + } +} + ?> \ No newline at end of file diff --git a/modules/base/classes/cache.php b/modules/base/classes/cache.php index b15274590..7c248b192 100644 --- a/modules/base/classes/cache.php +++ b/modules/base/classes/cache.php @@ -24,234 +24,234 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_cache { - var $cache; - var $statistics = array('warm' => 0, 'cold' => 0, 'miss' => 0, 'replaced' => 0, 'added' => 0, 'removed' => 0, 'dirty' => 0); - var $cache_id = 1; // default cache id - var $collections; - var $dirty_collections; - var $dirty_objs = array(); - var $global_collections = array(); - var $collection_expiration_periods = array(); - var $e; + var $cache; + var $statistics = array('warm' => 0, 'cold' => 0, 'miss' => 0, 'replaced' => 0, 'added' => 0, 'removed' => 0, 'dirty' => 0); + var $cache_id = 1; // default cache id + var $collections; + var $dirty_collections; + var $dirty_objs = array(); + var $global_collections = array(); + var $collection_expiration_periods = array(); + var $e; - /** - * Constructor - * - * Takes cache directory as param - * - * @param $cache_dir string - */ - function __construct($cache_dir = '') { - - $this->e = owa_coreAPI::errorSingleton(); - } - - function set($collection, $key, $value, $expires = '') { - - $hkey = $this->hash($key); - owa_coreAPI::debug('set key: '.$key); - owa_coreAPI::debug('set hkey: '.$hkey); - $this->cache[$collection][$hkey] = $value; - $this->debug(sprintf('Added Object to Cache - Collection: %s, id: %s', $collection, $hkey)); - $this->statistics['added']++; - $this->dirty_objs[$collection][$hkey] = $hkey; - $this->dirty_collections[$collection] = true; - $this->debug(sprintf('Added Object to Dirty List - Collection: %s, id: %s', $collection, $hkey)); - $this->statistics['dirty']++; - - } - - function replace($collection, $key, $value) { - - $hkey = $this->hash($key); - $this->cache[$collection][$hkey] = $value; - $this->debug(sprintf('Replacing Object in Cache - Collection: %s, id: %s', $collection, $hkey)); - $this->statistics['replaced']++; - - // check to make sure the dirty collection exists and object is not already in there. - if (!empty($this->dirty_objs[$collection])) { - if(!in_array($hkey, $this->dirty_objs[$collection])) { - $this->dirty_objs[$collection][] = $hkey; - $this->dirty_collections[$collection] = true; - $this->debug(sprintf('Added Object to Dirty List - Collection: %s, id: %s', $collection, $hkey)); - $this->statistics['dirty']++; - } - } else { - $this->dirty_objs[$collection][] = $hkey; - $this->dirty_collections[$collection] = true; - $this->debug(sprintf('Added Object to Dirty List - Collection: %s, id: %s', $collection, $hkey)); - $this->statistics['dirty']++; - } - - - } - - function get($collection, $key) { - - $id = $this->hash($key); - // check warm cache and return - if (isset($this->cache[$collection][$id])) { - $this->debug(sprintf('CACHE HIT (Warm) - Retrieved Object from Cache - Collection: %s, id: %s', $collection, $id)); - $this->statistics['warm']++; - //load from cache file - } else { - - $item = $this->getItemFromCacheStore($collection, $id); - if ($item) { - $this->cache[$collection][$id] = $item; - $this->debug(sprintf('CACHE HIT (Cold) - Retrieved Object from Cache File - Collection: %s, id: %s', $collection, $id)); - $this->statistics['cold']++; - } else { - $this->debug( sprintf( 'CACHE MISS - object not found for Collection: %s, id: %s', $collection, $id ) ); - $this->statistics['miss']++; - } - } - - if (isset($this->cache[$collection][$id])) { - return $this->cache[$collection][$id]; - } else { - return false; - } - - } - - function remove($collection, $key) { - - $id = $this->hash($key); - unset($this->cache[$collection][$id]); - return $this->removeItemFromCacheStore($collection, $id); - - } - - function persistCache() { - - $this->debug("starting to persist cache..."); - - // check for dirty objects - if (!empty($this->dirty_objs)) { - - $this->debug('Dirty Objects: '.print_r($this->dirty_objs, true)); - $this->debug("starting to persist cache..."); - - // persist dirty objects - foreach ($this->dirty_objs as $collection => $ids) { - - foreach ($ids as $id) { - $this->putItemToCacheStore($collection, $id); - } - } - - } else { - $this->debug("There seem to be no dirty objects in the cache to persist."); - } - } - - /** - * Store specific implementation of getting an object from the cold cache store - */ - function getItemFromCacheStore($collection, $id) { - return false; - } - /** - * Store specific implementation of putting an object to the cold cache store - */ - function putItemToCacheStore($collection, $id) { - return false; - } - - /** - * Store specific implementation of removing an object to the cold cache store - */ - function removeItemFromCacheStore($collection, $id) { - return false; - } - - /** - * Store specific implementation of flushing the cold cache store - */ - function flush() { - - return false; - } - - function getStats() { - - return sprintf("Cache Statistics: - Total Hits: %s (Warm/Cold: %s/%s) - Total Miss: %s - Total Added to Cache: %s - Total Replaced: %s - Total Persisted: %s - Total Removed: %s", - $this->statistics['warm'] + $this->statistics['cold'], - $this->statistics['warm'], - $this->statistics['cold'], - $this->statistics['miss'], - $this->statistics['added'], - $this->statistics['replaced'], - $this->statistics['dirty'], - $this->statistics['removed']); - } - - function prepare($obj) { - - return $obj; - } - - function __destruct() { - - $this->persistCache(); - $this->debug($this->getStats()); - $this->persistStats(); - } - - function persistStats() { - - return false; - } - - function hash($id) { - - return md5($id); - } - - function debug($msg) { - - return owa_coreAPI::debug($msg); - } - - function error($msg) { - - return false; - } - - function setCollectionExpirationPeriod($collection_name, $seconds) { - - $this->collection_expiration_periods[$collection_name] = $seconds; - } - - function getCollectionExpirationPeriod($collection_name) { - - // for some reason an 'array_key_exists' check does not work here. using isset instead. - if (isset($this->collection_expiration_periods[$collection_name])) { - return $this->collection_expiration_periods[$collection_name]; - } else { - return false; - } - } - - function setGlobalCollection($collection) { - - return $this->global_collections[] = $collection; - - } + /** + * Constructor + * + * Takes cache directory as param + * + * @param $cache_dir string + */ + function __construct($cache_dir = '') { + + $this->e = owa_coreAPI::errorSingleton(); + } + + function set($collection, $key, $value, $expires = '') { + + $hkey = $this->hash($key); + owa_coreAPI::debug('set key: '.$key); + owa_coreAPI::debug('set hkey: '.$hkey); + $this->cache[$collection][$hkey] = $value; + $this->debug(sprintf('Added Object to Cache - Collection: %s, id: %s', $collection, $hkey)); + $this->statistics['added']++; + $this->dirty_objs[$collection][$hkey] = $hkey; + $this->dirty_collections[$collection] = true; + $this->debug(sprintf('Added Object to Dirty List - Collection: %s, id: %s', $collection, $hkey)); + $this->statistics['dirty']++; + + } + + function replace($collection, $key, $value) { + + $hkey = $this->hash($key); + $this->cache[$collection][$hkey] = $value; + $this->debug(sprintf('Replacing Object in Cache - Collection: %s, id: %s', $collection, $hkey)); + $this->statistics['replaced']++; + + // check to make sure the dirty collection exists and object is not already in there. + if (!empty($this->dirty_objs[$collection])) { + if(!in_array($hkey, $this->dirty_objs[$collection])) { + $this->dirty_objs[$collection][] = $hkey; + $this->dirty_collections[$collection] = true; + $this->debug(sprintf('Added Object to Dirty List - Collection: %s, id: %s', $collection, $hkey)); + $this->statistics['dirty']++; + } + } else { + $this->dirty_objs[$collection][] = $hkey; + $this->dirty_collections[$collection] = true; + $this->debug(sprintf('Added Object to Dirty List - Collection: %s, id: %s', $collection, $hkey)); + $this->statistics['dirty']++; + } + + + } + + function get($collection, $key) { + + $id = $this->hash($key); + // check warm cache and return + if (isset($this->cache[$collection][$id])) { + $this->debug(sprintf('CACHE HIT (Warm) - Retrieved Object from Cache - Collection: %s, id: %s', $collection, $id)); + $this->statistics['warm']++; + //load from cache file + } else { + + $item = $this->getItemFromCacheStore($collection, $id); + if ($item) { + $this->cache[$collection][$id] = $item; + $this->debug(sprintf('CACHE HIT (Cold) - Retrieved Object from Cache File - Collection: %s, id: %s', $collection, $id)); + $this->statistics['cold']++; + } else { + $this->debug( sprintf( 'CACHE MISS - object not found for Collection: %s, id: %s', $collection, $id ) ); + $this->statistics['miss']++; + } + } + + if (isset($this->cache[$collection][$id])) { + return $this->cache[$collection][$id]; + } else { + return false; + } + + } + + function remove($collection, $key) { + + $id = $this->hash($key); + unset($this->cache[$collection][$id]); + return $this->removeItemFromCacheStore($collection, $id); + + } + + function persistCache() { + + $this->debug("starting to persist cache..."); + + // check for dirty objects + if (!empty($this->dirty_objs)) { + + $this->debug('Dirty Objects: '.print_r($this->dirty_objs, true)); + $this->debug("starting to persist cache..."); + + // persist dirty objects + foreach ($this->dirty_objs as $collection => $ids) { + + foreach ($ids as $id) { + $this->putItemToCacheStore($collection, $id); + } + } + + } else { + $this->debug("There seem to be no dirty objects in the cache to persist."); + } + } + + /** + * Store specific implementation of getting an object from the cold cache store + */ + function getItemFromCacheStore($collection, $id) { + return false; + } + /** + * Store specific implementation of putting an object to the cold cache store + */ + function putItemToCacheStore($collection, $id) { + return false; + } + + /** + * Store specific implementation of removing an object to the cold cache store + */ + function removeItemFromCacheStore($collection, $id) { + return false; + } + + /** + * Store specific implementation of flushing the cold cache store + */ + function flush() { + + return false; + } + + function getStats() { + + return sprintf("Cache Statistics: + Total Hits: %s (Warm/Cold: %s/%s) + Total Miss: %s + Total Added to Cache: %s + Total Replaced: %s + Total Persisted: %s + Total Removed: %s", + $this->statistics['warm'] + $this->statistics['cold'], + $this->statistics['warm'], + $this->statistics['cold'], + $this->statistics['miss'], + $this->statistics['added'], + $this->statistics['replaced'], + $this->statistics['dirty'], + $this->statistics['removed']); + } + + function prepare($obj) { + + return $obj; + } + + function __destruct() { + + $this->persistCache(); + $this->debug($this->getStats()); + $this->persistStats(); + } + + function persistStats() { + + return false; + } + + function hash($id) { + + return md5($id); + } + + function debug($msg) { + + return owa_coreAPI::debug($msg); + } + + function error($msg) { + + return false; + } + + function setCollectionExpirationPeriod($collection_name, $seconds) { + + $this->collection_expiration_periods[$collection_name] = $seconds; + } + + function getCollectionExpirationPeriod($collection_name) { + + // for some reason an 'array_key_exists' check does not work here. using isset instead. + if (isset($this->collection_expiration_periods[$collection_name])) { + return $this->collection_expiration_periods[$collection_name]; + } else { + return false; + } + } + + function setGlobalCollection($collection) { + + return $this->global_collections[] = $collection; + + } } ?> \ No newline at end of file diff --git a/modules/base/classes/calculatedMetric.php b/modules/base/classes/calculatedMetric.php index 0ef52d635..3ac288d16 100644 --- a/modules/base/classes/calculatedMetric.php +++ b/modules/base/classes/calculatedMetric.php @@ -24,35 +24,35 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 + * @version $Revision$ + * @since owa 1.3.0 */ class owa_calculatedMetric extends owa_metric { - - var $is_calculated = true; - var $child_metrics = array(); - var $formula; - - function setChildMetric($name) { - - $this->child_metrics[] = $name; - } - - function getChildMetrics() { - - return $this->child_metrics; - } - - function setFormula($string) { - - $this->formula = $string; - } - - function getFormula() { - - return $this->formula; - } + + var $is_calculated = true; + var $child_metrics = array(); + var $formula; + + function setChildMetric($name) { + + $this->child_metrics[] = $name; + } + + function getChildMetrics() { + + return $this->child_metrics; + } + + function setFormula($string) { + + $this->formula = $string; + } + + function getFormula() { + + return $this->formula; + } } ?> \ No newline at end of file diff --git a/modules/base/classes/chartData.php b/modules/base/classes/chartData.php index ddae2d527..e92868420 100644 --- a/modules/base/classes/chartData.php +++ b/modules/base/classes/chartData.php @@ -24,95 +24,95 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_chartData { - var $series_data = array(); - var $series_labels = array(); - - function __construct() { - - return; - } - - function owa_chartData() { - - return owa_chartData::__construct(); - } - - function setSeries($name, $data, $label = '') { - - $this->series_data[$name] = $data; - $this->series_label[$name] = $label; - return; - } - - function getSeriesData($name) { - - if (array_key_exists($name, $this->series_data)) { - return $this->series_data[$name]; - } else { - return array(); - } - - } - - function getSeriesLabel($name) { - - if (array_key_exists($name, $this->series_label)) { - return $this->series_label[$name]; - } else { - return false; - } - } - - function getMin($name) { - - $min = min($this->getSeriesData($name)); - - if ($min >= 0) { - return 0; - } else { - return $min - 2; - } - - } - - function getMax($name, $name2 = null) { - - $max_values = array(); - - $max_values[] = max($this->getSeriesData($name)); - - if (!empty($name2)) { - $max_values[] = max($this->getSeriesData($name2)); - } - - $max = max($max_values); - - return $max + 2; - } - - function checkForSeries() { - - $counts = array(); - foreach ($this->series_data as $series) { - - $counts[] = count($series); - } - - if (array_sum($counts) > 0) { - return true; - } else { - return false; - } - } - - + var $series_data = array(); + var $series_labels = array(); + + function __construct() { + + return; + } + + function owa_chartData() { + + return owa_chartData::__construct(); + } + + function setSeries($name, $data, $label = '') { + + $this->series_data[$name] = $data; + $this->series_label[$name] = $label; + return; + } + + function getSeriesData($name) { + + if (array_key_exists($name, $this->series_data)) { + return $this->series_data[$name]; + } else { + return array(); + } + + } + + function getSeriesLabel($name) { + + if (array_key_exists($name, $this->series_label)) { + return $this->series_label[$name]; + } else { + return false; + } + } + + function getMin($name) { + + $min = min($this->getSeriesData($name)); + + if ($min >= 0) { + return 0; + } else { + return $min - 2; + } + + } + + function getMax($name, $name2 = null) { + + $max_values = array(); + + $max_values[] = max($this->getSeriesData($name)); + + if (!empty($name2)) { + $max_values[] = max($this->getSeriesData($name2)); + } + + $max = max($max_values); + + return $max + 2; + } + + function checkForSeries() { + + $counts = array(); + foreach ($this->series_data as $series) { + + $counts[] = count($series); + } + + if (array_sum($counts) > 0) { + return true; + } else { + return false; + } + } + + } diff --git a/modules/base/classes/cliController.php b/modules/base/classes/cliController.php index 430dae039..f3983d3fe 100644 --- a/modules/base/classes/cliController.php +++ b/modules/base/classes/cliController.php @@ -1,62 +1,62 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - -class owa_cliController extends owa_adminController { - - var $is_admin = true; - - /** - * Constructor - * - * @param array $params - * @return owa_controller - */ - function __construct($params) { - - if (owa_coreAPI::getSetting('base', 'cli_mode')) { - - return parent::__construct($params); - - } else { - - owa_coreAPI::notice("Controller not called from CLI"); - exit; - } - } - - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + +class owa_cliController extends owa_adminController { + + var $is_admin = true; + + /** + * Constructor + * + * @param array $params + * @return owa_controller + */ + function __construct($params) { + + if (owa_coreAPI::getSetting('base', 'cli_mode')) { + + return parent::__construct($params); + + } else { + + owa_coreAPI::notice("Controller not called from CLI"); + exit; + } + } + + +} + ?> \ No newline at end of file diff --git a/modules/base/classes/client.php b/modules/base/classes/client.php index 62f409395..d81725437 100644 --- a/modules/base/classes/client.php +++ b/modules/base/classes/client.php @@ -28,901 +28,901 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_client extends owa_caller { - var $commerce_event; - - var $pageview_event; - - var $global_event_properties = array(); - - var $stateInit; - - var $organicSearchEngines; - - // set one traffic has been attributed. - var $isTrafficAttributed; - - public function __construct($config = null) { - - parent::__construct($config); - - $this->pageview_event = $this->makeEvent(); - $this->pageview_event->setEventType('base.page_request'); - // Set the page url from environmental vars - $this->setGlobalEventProperty( 'page_url', owa_coreAPI::getCurrentUrl() ); - owa_coreAPI::registerStateStore('v', time()+3600*24*365*10, '', 'assoc', 'cookie', true); - owa_coreAPI::registerStateStore('s', time()+3600*24*365*10, '', 'assoc', 'cookie', true); - owa_coreAPI::registerStateStore('b', null, '', 'json', 'cookie', true); - $cwindow = owa_coreAPI::getSetting( 'base', 'campaignAttributionWindow' ); - owa_coreAPI::registerStateStore('c', time() + 3600 * 24 * $cwindow , '', 'json', 'cookie', true); - - $this->organicSearchEngines = array( - - array('d' => 'google', 'q' => 'q'), - array('d' => 'yahoo', 'q' => 'p'), - array('d' => 'msn', 'q' => 'q'), - array('d' => 'bing', 'q' => 'q'), - array('d' => 'images.google', 'q' => 'q'), - array('d' => 'images.search.yahoo.com', 'q' => 'p'), - array('d' => 'aol', 'q' => 'query'), - array('d' => 'aol', 'q' => 'encquery'), - array('d' => 'aol', 'q' => 'q'), - array('d' => 'lycos', 'q' => 'query'), - array('d' => 'ask', 'q' => 'q'), - array('d' => 'altavista', 'q' => 'q'), - array('d' => 'netscape', 'q' => 'query'), - array('d' => 'cnn', 'q' => 'query'), - array('d' => 'about', 'q' => 'terms'), - array('d' => 'mamma', 'q' => 'q'), - array('d' => 'daum', 'q' => 'q'), - array('d' => 'eniro', 'q' => 'search_word'), - array('d' => 'naver', 'q' => 'query'), - array('d' => 'pchome', 'q' => 'q'), - array('d' => 'alltheweb', 'q' => 'q'), - array('d' => 'voila', 'q' => 'rdata'), - array('d' => 'virgilio', 'q' => 'qs'), - array('d' => 'live', 'q' => 'q'), - array('d' => 'baidu', 'q' => 'wd'), - array('d' => 'alice', 'q' => 'qs'), - array('d' => 'yandex', 'q' => 'text'), - array('d' => 'najdi', 'q' => 'q'), - array('d' => 'mama', 'q' => 'query'), - array('d' => 'seznam', 'q' => 'q'), - array('d' => 'search', 'q' => 'q'), - array('d' => 'wp', 'q' => 'szukaj'), - array('d' => 'onet', 'q' => 'qt'), - array('d' => 'szukacz', 'q' => 'q'), - array('d' => 'yam', 'q' => 'k'), - array('d' => 'kvasir', 'q' => 'q'), - array('d' => 'sesam', 'q' => 'q'), - array('d' => 'ozu', 'q' => 'q'), - array('d' => 'terra', 'q' => 'query'), - array('d' => 'mynet', 'q' => 'q'), - array('d' => 'ekolay', 'q' => 'q'), - array('d' => 'rambler', 'q' => 'query'), - array('d' => 'rambler', 'q' => 'words') - ); - } - - public function setPageTitle($value) { - $this->pageview_event->set('page_title', $value); - } - - public function setPageType($value) { - $this->pageview_event->set('page_type', $value); - } - - public function setProperty($name, $value) { - $this->setGlobalEventProperty($name, $value); - } - - private function setGlobalEventProperty($name, $value) { - - $this->global_event_properties[$name] = $value; - } - - private function getGlobalEventProperty($name) { - - if ( array_key_exists($name, $this->global_event_properties) ) { - return $this->global_event_properties[$name]; - } - } - - private function deleteGlobalEventProperty( $name ) { - - if ( array_key_exists($name, $this->global_event_properties) ) { - unset($this->global_event_properties[$name]); - } - } - - private function manageState( &$event ) { - - if ( ! $this->stateInit ) { - - $this->setVisitorId( $event ); - $this->setFirstSessionTimestamp( $event ); - $this->setLastRequestTime( $event ); - $this->setSessionId( $event ); - $this->setNumberPriorSessions( $event ); - $this->setDaysSinceLastSession( $event ); - $this->setTrafficAttribution( $event ); - $this->stateInit = true; - } - } - - private function setVisitorId( &$event ) { - - $visitor_id = owa_coreAPI::getStateParam( 'v', 'vid' ); - - if ( ! $visitor_id ) { - $visitor_id = owa_coreAPI::getStateParam( 'v' ); - owa_coreAPI::clearState( 'v' ); - owa_coreAPI::setState( 'v', 'vid', $visitor_id, 'cookie', true ); - - } - - if ( ! $visitor_id ) { - $visitor_id = $event->getSiteSpecificGuid( $this->site_id ); - $this->setGlobalEventProperty( 'is_new_visitor', true ); - owa_coreAPI::setState( 'v', 'vid', $visitor_id, 'cookie', true ); - } - // set property on event object - $this->setGlobalEventProperty( 'visitor_id', $visitor_id ); - } - - private function setNumberPriorSessions( &$event ) { - // if check for nps value in vistor cookie. - $nps = owa_coreAPI::getStateParam('v', 'nps'); - - // if new session, increment visit count and persist to state store - if ( $this->getGlobalEventProperty('is_new_session' ) ) { - - // set value to 0 if not found. - if ( ! $nps ) { - - $nps = "0"; - - } else { - - $nps = $nps + 1; - } - - owa_coreAPI::setState('v', 'nps', $nps, 'cookie', true); - } - - // set property on the event object - $this->setGlobalEventProperty('nps', $nps); - } - - private function setFirstSessionTimestamp( &$event ) { - - $fsts = owa_coreAPI::getStateParam( 'v', 'fsts' ); - - if ( ! $fsts ) { - $fsts = $event->get('timestamp'); - owa_coreAPI::setState(owa_coreAPI::getSetting('base', 'visitor_param'), 'fsts', $fsts , 'cookie', true); - } - - $this->setGlobalEventProperty( 'fsts', $fsts ); - - // calc days since first session - $dsfs = round( ( $fsts - $event->get( 'timestamp' ) ) / ( 3600 * 24 ) ) ; - owa_coreAPI::setState(owa_coreAPI::getSetting('base', 'visitor_param'), 'dsfs', $dsfs , 'cookie', true); - $this->setGlobalEventProperty( 'dsfs', $dsfs ); - } - - private function setDaysSinceLastSession( &$event ) { - - owa_coreAPI::debug('setting days since last session.'); - $dsps = ''; - if ( $this->getGlobalEventProperty( 'is_new_session' ) ) { - owa_coreAPI::debug( 'timestamp: ' . $event->get( 'timestamp' ) ); - $last_req = $this->getGlobalEventProperty( 'last_req' ); - if ( ! $last_req ) { - $last_req = $event->get( 'timestamp' ); - } - owa_coreAPI::debug( 'last_req: ' . $last_req ); - $dsps = round( ( $event->get( 'timestamp' ) - $last_req ) / ( 3600*24 ) ); - owa_coreAPI::setState('s', 'dsps', $dsps , 'cookie', true); - } - - if ( ! $dsps ) { - $dsps = owa_coreAPI::getState( 's', 'dsps' ); - - if ( ! $dsps ) { - $dsps = 0; - } - } - - $this->setGlobalEventProperty( 'dsps', $dsps ); - } - - private function setSessionId( &$event ) { - - $is_new_session = $this->isNewSession( $event->get( 'timestamp' ), $this->getGlobalEventProperty( 'last_req' ) ); - if ( $is_new_session ) { - //set prior_session_id - $prior_session_id = owa_coreAPI::getStateParam('s', 'sid'); - if ( ! $prior_session_id ) { - $state_store_name = sprintf('%s_%s', owa_coreAPI::getSetting('base', 'site_session_param'), $this->site_id); - $prior_session_id = owa_coreAPI::getStateParam($state_store_name, 's'); - } - if ($prior_session_id) { - $this->setGlobalEventProperty( 'prior_session_id', $prior_session_id ); - } - - $this->resetSessionState(); - - $session_id = $event->getSiteSpecificGuid( $this->site_id ); - - //mark new session flag on current request - $this->setGlobalEventProperty( 'is_new_session', true ); - owa_coreAPI::setState( 's', 'sid', $session_id, 'cookie', true ); - - } else { - // Must be an active session so just pull the session id from the state store - $session_id = owa_coreAPI::getStateParam('s', 'sid'); - - // support for old style cookie - if ( ! $session_id ) { - $state_store_name = sprintf('%s_%s', owa_coreAPI::getSetting('base', 'site_session_param'), $this->site_id); - $session_id = owa_coreAPI::getStateParam($state_store_name, 's'); - - } - - // fail-safe just in case there is no session_id - if ( ! $session_id ) { - $session_id = $event->getSiteSpecificGuid( $this->site_id ); - //mark new session flag on current request - $this->setGlobalEventProperty( 'is_new_session', true ); - owa_coreAPI::debug('setting failsafe session id'); - } - } - - // set global event property - $this->setGlobalEventProperty( 'session_id', $session_id ); - // set sid state - owa_coreAPI::setState( 's', 'sid', $session_id, 'cookie', true ); - } - - private function setLastRequestTime( &$event ) { - - $last_req = owa_coreAPI::getStateParam('s', 'last_req'); - - // suppport for old style cookie - if ( ! $last_req ) { - $state_store_name = sprintf( '%s_%s', owa_coreAPI::getSetting( 'base', 'site_session_param' ), $this->site_id ); - $last_req = owa_coreAPI::getStateParam( $state_store_name, 'last_req' ); - } - // set property on event object - $this->setGlobalEventProperty( 'last_req', $last_req ); - owa_coreAPI::debug("setting last_req value of $last_req as global event property."); - // store new state value - owa_coreAPI::setState( 's', 'last_req', $event->get( 'timestamp' ), 'cookie', true ); - } - - /** - * Check to see if request is a new or active session - * - * @return boolean - */ - private function isNewSession($timestamp = '', $last_req = 0) { - - $is_new_session = false; - - if ( ! $timestamp ) { - $timestamp = time(); - } - - $time_since_lastreq = $timestamp - $last_req; - $len = owa_coreAPI::getSetting( 'base', 'session_length' ); - if ( $time_since_lastreq < $len ) { - owa_coreAPI::debug("This request is part of a active session."); - return false; - } else { - //NEW SESSION. prev session expired, because no requests since some time. - owa_coreAPI::debug("This request is the start of a new session. Prior session expired."); - return true; - } - } - - /** - * Logs tracking event from url params taken from request scope. - * Takes event type from url. - * - * @return unknown - */ - function logEventFromUrl($manage_state = false) { - - // keeps php executing even if the client closes the connection - ignore_user_abort(true); - $service = owa_coreAPI::serviceSingleton(); - $service->request->decodeRequestParams(); - $event = owa_coreAPI::supportClassFactory('base', 'event'); - $event->setEventType(owa_coreAPI::getRequestParam('event_type')); - $event->setProperties($service->request->getAllOwaParams()); - - // check for third party cookie mode. - $mode = owa_coreAPI::getRequestParam('thirdParty'); - if ( $mode ) { - return $this->trackEvent($event); - } else { - return owa_coreAPI::logEvent($event->getEventType(), $event); - } - } - - /** - * Logs tracking event - * - * This function fires a tracking event that will be processed and then dispatched - * - * @param object $event - * @return boolean - */ - public function trackEvent($event) { - - // do not track anything if user is in overlay mode - if (owa_coreAPI::getStateParam('overlay')) { - return false; - } - - $this->setGlobalEventProperty( 'HTTP_REFERER', owa_coreAPI::getServerParam('HTTP_REFERER') ); - - // needed by helper page tags function so it can append to first hit tag url - if (!$this->getSiteId()) { - $this->setSiteId($event->get('site_id')); - } - - if (!$this->getSiteId()) { - $this->setSiteId(owa_coreAPI::getRequestParam('site_id')); - } - - // set various state properties. - $this->manageState( $event ); - - $event = $this->setAllGlobalEventProperties( $event ); - - // send event to log API for processing. - return owa_coreAPI::logEvent($event->getEventType(), $event); - } - - public function setAllGlobalEventProperties( $event ) { - - if ( ! $event->get('site_id') ) { - $event->set( 'site_id', $this->getSiteId() ); - } - - // add custom variables to global properties if not there already - for ( $i=1; $i <= owa_coreAPI::getSetting('base', 'maxCustomVars'); $i++ ) { - $cv_param_name = 'cv' . $i; - $cv_value = ''; - - // if the custom var is not already a global property - if ( ! $this->getGlobalEventProperty( $cv_param_name ) ) { - // check to see if it exists - $cv_value = $this->getCustomVar( $i ); - // if so add it - if ( $cv_value ) { - $this->setGlobalEventProperty( $cv_param_name, $cv_value ); - } - } - } - - // merge global event properties - $event->setNewProperties( $this->global_event_properties ); - - return $event; - - } - - public function getAllEventProperties( $event ) { - - $event = $this->setAllGlobalEventProperties( $event ); - return $event->getProperties(); - } - - public function trackPageview($event = '') { - - if ($event) { - $event->setEventType('base.page_request'); - $this->pageview_event = $event; - } - return $this->trackEvent($this->pageview_event); - } - - public function trackAction($action_group = '', $action_name, $action_label = '', $numeric_value = 0) { - - $event = $this->makeEvent(); - $event->setEventType('track.action'); - $event->set('action_group', $action_group); - $event->set('action_name', $action_name); - $event->set('action_label', $action_label); - $event->set('numeric_value', $numeric_value); - $event->set('site_id', $this->getSiteId()); - return $this->trackEvent($event); - } - - /** - * Creates a ecommerce Transaction event - * - * Creates a parent commerce.transaction event - */ - public function addTransaction( - $order_id, - $order_source = '', - $total = 0, - $tax = 0, - $shipping = 0, - $gateway = '', - $country = '', - $state = '', - $city = '', - $page_url = '', - $session_id = '' - ) { - - $this->commerce_event = $this->makeEvent(); - $this->commerce_event->setEventType( 'ecommerce.transaction' ); - $this->commerce_event->set( 'ct_order_id', $order_id ); - $this->commerce_event->set( 'ct_order_source', $order_source ); - $this->commerce_event->set( 'ct_total', $total ); - $this->commerce_event->set( 'ct_tax', $tax ); - $this->commerce_event->set( 'ct_shipping', $shipping ); - $this->commerce_event->set( 'ct_gateway', $gateway ); - $this->commerce_event->set( 'page_url', $page_url ); - $this->commerce_event->set( 'ct_line_items', array() ); - $this->commerce_event->set( 'country', $country ); - $this->commerce_event->set( 'state', $state ); - $this->commerce_event->set( 'city', $city ); - if ( $session_id ) { - $this->commerce_event->set( 'original_session_id', $session_id ); - // tells the client to NOT manage state properties as we are - // going to look them up from the session later. - $this->commerce_event->set( 'is_state_set', true ); - } - } - - /** - * Adds a line item to a commerce transaction - * - * Creates and a commerce.line_item event and adds it to the parent transaction event - */ - public function addTransactionLineItem($order_id, $sku = '', $product_name = '', $category = '', $unit_price = 0, $quantity = 0) { - - if ( empty( $this->commerce_event ) ) { - $this->addTransaction('none set'); - } - - $li = array(); - $li['li_order_id'] = $order_id ; - $li['li_sku'] = $sku ; - $li['li_product_name'] = $product_name ; - $li['li_category'] = $category ; - $li['li_unit_price'] = $unit_price ; - $li['li_quantity'] = $quantity ; - - $items = $this->commerce_event->get( 'ct_line_items' ); - $items[] = $li; - $this->commerce_event->set( 'ct_line_items', $items ); - } - - /** - * tracks a commerce events - * - * Tracks a parent transaction event by sending it to the event queue - */ - public function trackTransaction() { - - if ( ! empty( $this->commerce_event ) ) { - $this->trackEvent( $this->commerce_event ); - $this->commerce_event = ''; - } - } - - public function createSiteId($value) { - - return md5($value); - } - - public function setCampaignNameKey( $key ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_params[ 'campaign' ] = $key; - owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); - } - - public function setCampaignMediumKey( $key ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_params[ 'medium' ] = $key; - owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); - } - - public function setCampaignSourceKey( $key ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_params[ 'source' ] = $key; - owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); - } - - public function setCampaignSearchTermsKey( $key ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_params[ 'search_terms' ] = $key; - owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); - } - - public function setCampaignAdKey( $key ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_params[ 'ad' ] = $key; - owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); - } - - public function setCampaignAdTypeKey( $key ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_params[ 'ad_type' ] = $key; - owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); - } - - public function setUserName( $value ) { - - $this->setGlobalEventProperty( 'user_name', $value ); - } - - function getCampaignProperties( $event ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - $campaign_properties = array(); - $campaign_state = array(); - $request = owa_coreAPI::getRequest(); - foreach ( $campaign_params as $k => $param ) { - //look for property on the event - $property = $event->get( $param ); - - // look for property on the request scope. - if ( ! $property ) { - $property = $request->getRequestParam( $param ); - } - if ( $property ) { - $campaign_properties[ $k ] = $property; - } - } - - // backfill values for incomplete param combos - - if (array_key_exists('ad_type', $campaign_properties) && !array_key_exists('ad', $campaign_properties)) { - $campaign_properties['ad'] = '(not set)'; - } - - if (array_key_exists('ad', $campaign_properties) && !array_key_exists('ad_type', $campaign_properties)) { - $campaign_properties['ad_type'] = '(not set)'; - } - - if (!empty($campaign_properties)) { - //$campaign_properties['ts'] = $event->get('timestamp'); - } - - owa_coreAPI::debug('campaign properties: '. print_r($campaign_properties, true)); - - return $campaign_properties; - } - - private function setCampaignSessionState( $properties ) { - - $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); - foreach ($campaign_params as $k => $v) { - - if (array_key_exists( $k, $properties ) ) { - - owa_coreAPI::setState( 's', $k, $properties[$k] ); - } - } - } - - function directAttributionModel( &$campaign_properties ) { - - // add new campaign info to existing campaign cookie. - if ( $campaign_properties ) { - - // get prior campaing touches from c cookie - $campaign_state = $this->getCampaignState(); - - // add new campaign into state array - $campaign_state[] = (object) $campaign_properties; - - // if more than x slice the first one off to make room - $count = count( $campaign_state ); - $max = owa_coreAPI::getSetting( 'base', 'max_prior_campaigns'); - if ($count > $max ) { - array_shift( $campaign_state ); - } - - // reset state - $this->setCampaignCookie($campaign_state); - - // set flag - $this->isTrafficAttributed = true; - - // persist state to session store - $this->setCampaignSessionState( $campaign_properties ); - } - - } - - function originalAttributionModel( &$campaign_properties ) { - - $campaign_state = $this->getCampaignState(); - // orignal touch was set previously. jus use that. - if (!empty($campaign_state)) { - // do nothing - // set the attributes from the first campaign touch - $campaign_properties = $campaign_state[0]; - $this->isTrafficAttributed = true; - - // no orginal touch, set one if it's a new campaign touch - } else { - - if (!empty($campaign_properties)) { - // add timestamp - //$campaign_properties['ts'] = $event->get('timestamp'); - owa_coreAPI::debug('Setting original Campaign attrbution.'); - $campaign_state[] = $campaign_properties; - // set cookie - $this->setCampaignCookie($campaign_state); - $this->isTrafficAttributed = true; - } - } - - // persist state to session store - $this->setCampaignSessionState( $campaign_properties ); - } - - function getCampaignState() { - - $campaign_state = owa_coreAPI::getState( 'c', 'attribs' ); - if ( ! $campaign_state ) { - - $campaign_state = array(); - } - - return $campaign_state; - } - - function setTrafficAttribution( &$event ) { - - // if not then look for individual campaign params on the request. - // this happens when the client is php and the params are on the url - $campaign_properties = $this->getCampaignProperties( $event ); - if ( $campaign_properties ) { - $campaign_properties['ts'] = $event->get('timestamp'); - } - - // choose attribution model. - $model = owa_coreAPI::getSetting('base', 'trafficAttributionMode'); - switch ( $model ) { - - case 'direct': - owa_coreAPI::debug( 'Applying "Direct" Traffic Attribution Model' ); - $this->directAttributionModel( $campaign_properties ); - break; - case 'original': - owa_coreAPI::debug( 'Applying "Original" Traffic Attribution Model' ); - $this->originalAttributionModel( $campaign_properties ); - break; - default: - owa_coreAPI::debug( 'Applying Default (Direct) Traffic Attribution Model' ); - $this->directAttributionModel( $campaign_properties ); - } - - // if one of the attribution methods attributes the traffic them - // set attribution properties on the event object - if ( $this->isTrafficAttributed ) { - - owa_coreAPI::debug( 'Attributing Traffic to: %s', print_r($campaign_properties, true ) ); - - } else { - // infer the attribution from the referer - // if the request is the start of a new session - if ( $this->getGlobalEventProperty( 'is_new_session' ) ) { - owa_coreAPI::debug( 'Infering traffic attribution.' ); - $this->inferTrafficAttribution(); - } - } - - // apply traffic attribution realted properties to events - // all properties should be set in the state store by this point. - $campaign_params = owa_coreAPI::getSetting('base', 'campaign_params'); - foreach( $campaign_params as $k => $v ) { - - $value = owa_coreAPI::getState( 's', $k ); - - if ( $value ) { - $this->setGlobalEventProperty( $k, $value ); - } - } - - // set sesion referer - $session_referer = owa_coreAPI::getState('s', 'referer'); - if ( $session_referer ) { - - $this->setGlobalEventProperty( 'session_referer', $session_referer ); - } - - // set campaign touches - $campaign_state = owa_coreAPI::getState('c', 'attribs'); - if ( $campaign_state ) { - - $this->setGlobalEventProperty( 'attribs', json_encode( $campaign_state )); - } - } - - private function inferTrafficAttribution() { - - $ref = owa_coreAPI::getServerParam('HTTP_REFERER'); - $medium = 'direct'; - $source = '(none)'; - $search_terms = '(none)'; - $session_referer = '(none)'; - - if ( $ref ) { - $uri = owa_lib::parse_url( $ref ); - - // check for external referer - $host = owa_coreAPI::getServerParam('HTTP_HOST'); - if ( $host != $uri['host'] ) { - - $medium = 'referral'; - $source = owa_lib::stripWwwFromDomain( $uri['host'] ); - $engine = $this->isRefererSearchEngine( $uri ); - $session_referer = $ref; - if ( $engine ) { - $medium = 'organic-search'; - $search_terms = $engine['t']; - } - } - } - - owa_coreAPI::setState('s', 'referer', $session_referer); - owa_coreAPI::setState('s', 'medium', $medium); - owa_coreAPI::setState('s', 'source', $source); - owa_coreAPI::setState('s', 'search_terms', $search_terms); - } - - private function isRefererSearchEngine( $uri ) { - - if ( isset( $uri['host'] ) ) { - $host = $uri['host']; - } else { - return; - } - - foreach ( $this->organicSearchEngines as $engine ) { - - $domain = $engine['d']; - $query_param = $engine['q']; - $term = ''; - - if ( isset ($uri['query_params'][$query_param] ) ) { - $term = $uri['query_params'][$query_param]; - } - - if ( strpos($host, $domain) ) { - owa_coreAPI::debug( 'Found search engine: %s with query param %s:, query term: %s', $domain, $query_param, $term); - - return array('d' => $domain, 'q' => $query_param, 't' => $term ); - } - } - } - - function setCampaignCookie($values) { - // reset state - owa_coreAPI::setState('c', 'attribs', $values); - } - - // sets cookies domain - function setCookieDomain($domain) { - - if (!empty($domain)) { - $c = owa_coreAPI::configSingleton(); - // sanitizes the domain - $c->setCookieDomain($domain); - } - } - - /** - * Set a custom variable - * - * @param slot int the identifying number for the custom variable. 1-5. - * @param name string the key of the custom variable. - * @param value string the value of the varible - * @param scope string the scope of the variable. can be page, session, or visitor - */ - public function setCustomVar( $slot, $name, $value, $scope = '' ) { - - $cv_param_name = 'cv' . $slot; - $cv_param_value = $name . '=' . $value; - - if ( strlen( $cv_param_value ) > 65 ) { - owa_coreAPI::debug('Custom variable name + value is too large. Must be less than 64 characters.'); - return; - } - - switch ( $scope ) { - - case 'session': - - // store in session cookie - owa_coreAPI::setState( 'b', $cv_param_name, $cv_param_value ); - owa_coreAPI::debug( 'just set custom var on session.' ); - break; - - case 'visitor': - - // store in visitor cookie - owa_coreAPI::setState( 'v', $cv_param_name, $cv_param_value ); - // remove slot from session level cookie - owa_coreAPI::clearState( 'b', $cv_param_name ); - break; - } - - $this->setGlobalEventProperty( $cv_param_name, $cv_param_value ); - } - - public function getCustomVar( $slot ) { - - $cv_param_name = 'cv' . $slot; - $cv = ''; - // check request/page level - $cv = $this->getGlobalEventProperty( $cv_param_name ); - //check session store - if ( ! $cv ) { - $cv = owa_coreAPI::getState( 'b', $cv_param_name ); - } - // check visitor store - if ( ! $cv ) { - $cv = owa_coreAPI::getState( 'v', $cv_param_name ); - } - - return $cv; - - } - - public function deleteCustomVar( $slot ) { - - $cv_param_name = 'cv' . $slot; - //clear session level - owa_coreAPI::clearState( 'b', $cv_param_name ); - //clear visitor level - owa_coreAPI::clearState( 'v', $cv_param_name ); - // clear page level - $this->deleteGlobalEventProperty( $cv_param_name ); - - owa_coreAPI::debug("Deleting custom variable named $cv_param_name in slot $slot."); - } - - private function resetSessionState() { - - $last_req = owa_coreAPI::getState( 's', 'last_req' ); - owa_coreAPI::clearState( 's' ); - owa_coreAPI::setState( 's', 'last_req', $last_req); - } - - public function addOrganicSearchEngine( $domain, $query_param, $prepend = '' ) { - - $engine = array('d' => $domain, 'q' => $query_param); - if ( $prepend) { - array_unshift($this->organicSearchEngines, $engine ); - } else { - $this->organicSearchEngines[] = $engine; - } - } + var $commerce_event; + + var $pageview_event; + + var $global_event_properties = array(); + + var $stateInit; + + var $organicSearchEngines; + + // set one traffic has been attributed. + var $isTrafficAttributed; + + public function __construct($config = null) { + + parent::__construct($config); + + $this->pageview_event = $this->makeEvent(); + $this->pageview_event->setEventType('base.page_request'); + // Set the page url from environmental vars + $this->setGlobalEventProperty( 'page_url', owa_coreAPI::getCurrentUrl() ); + owa_coreAPI::registerStateStore('v', time()+3600*24*365*10, '', 'assoc', 'cookie', true); + owa_coreAPI::registerStateStore('s', time()+3600*24*365*10, '', 'assoc', 'cookie', true); + owa_coreAPI::registerStateStore('b', null, '', 'json', 'cookie', true); + $cwindow = owa_coreAPI::getSetting( 'base', 'campaignAttributionWindow' ); + owa_coreAPI::registerStateStore('c', time() + 3600 * 24 * $cwindow , '', 'json', 'cookie', true); + + $this->organicSearchEngines = array( + + array('d' => 'google', 'q' => 'q'), + array('d' => 'yahoo', 'q' => 'p'), + array('d' => 'msn', 'q' => 'q'), + array('d' => 'bing', 'q' => 'q'), + array('d' => 'images.google', 'q' => 'q'), + array('d' => 'images.search.yahoo.com', 'q' => 'p'), + array('d' => 'aol', 'q' => 'query'), + array('d' => 'aol', 'q' => 'encquery'), + array('d' => 'aol', 'q' => 'q'), + array('d' => 'lycos', 'q' => 'query'), + array('d' => 'ask', 'q' => 'q'), + array('d' => 'altavista', 'q' => 'q'), + array('d' => 'netscape', 'q' => 'query'), + array('d' => 'cnn', 'q' => 'query'), + array('d' => 'about', 'q' => 'terms'), + array('d' => 'mamma', 'q' => 'q'), + array('d' => 'daum', 'q' => 'q'), + array('d' => 'eniro', 'q' => 'search_word'), + array('d' => 'naver', 'q' => 'query'), + array('d' => 'pchome', 'q' => 'q'), + array('d' => 'alltheweb', 'q' => 'q'), + array('d' => 'voila', 'q' => 'rdata'), + array('d' => 'virgilio', 'q' => 'qs'), + array('d' => 'live', 'q' => 'q'), + array('d' => 'baidu', 'q' => 'wd'), + array('d' => 'alice', 'q' => 'qs'), + array('d' => 'yandex', 'q' => 'text'), + array('d' => 'najdi', 'q' => 'q'), + array('d' => 'mama', 'q' => 'query'), + array('d' => 'seznam', 'q' => 'q'), + array('d' => 'search', 'q' => 'q'), + array('d' => 'wp', 'q' => 'szukaj'), + array('d' => 'onet', 'q' => 'qt'), + array('d' => 'szukacz', 'q' => 'q'), + array('d' => 'yam', 'q' => 'k'), + array('d' => 'kvasir', 'q' => 'q'), + array('d' => 'sesam', 'q' => 'q'), + array('d' => 'ozu', 'q' => 'q'), + array('d' => 'terra', 'q' => 'query'), + array('d' => 'mynet', 'q' => 'q'), + array('d' => 'ekolay', 'q' => 'q'), + array('d' => 'rambler', 'q' => 'query'), + array('d' => 'rambler', 'q' => 'words') + ); + } + + public function setPageTitle($value) { + $this->pageview_event->set('page_title', $value); + } + + public function setPageType($value) { + $this->pageview_event->set('page_type', $value); + } + + public function setProperty($name, $value) { + $this->setGlobalEventProperty($name, $value); + } + + private function setGlobalEventProperty($name, $value) { + + $this->global_event_properties[$name] = $value; + } + + private function getGlobalEventProperty($name) { + + if ( array_key_exists($name, $this->global_event_properties) ) { + return $this->global_event_properties[$name]; + } + } + + private function deleteGlobalEventProperty( $name ) { + + if ( array_key_exists($name, $this->global_event_properties) ) { + unset($this->global_event_properties[$name]); + } + } + + private function manageState( &$event ) { + + if ( ! $this->stateInit ) { + + $this->setVisitorId( $event ); + $this->setFirstSessionTimestamp( $event ); + $this->setLastRequestTime( $event ); + $this->setSessionId( $event ); + $this->setNumberPriorSessions( $event ); + $this->setDaysSinceLastSession( $event ); + $this->setTrafficAttribution( $event ); + $this->stateInit = true; + } + } + + private function setVisitorId( &$event ) { + + $visitor_id = owa_coreAPI::getStateParam( 'v', 'vid' ); + + if ( ! $visitor_id ) { + $visitor_id = owa_coreAPI::getStateParam( 'v' ); + owa_coreAPI::clearState( 'v' ); + owa_coreAPI::setState( 'v', 'vid', $visitor_id, 'cookie', true ); + + } + + if ( ! $visitor_id ) { + $visitor_id = $event->getSiteSpecificGuid( $this->site_id ); + $this->setGlobalEventProperty( 'is_new_visitor', true ); + owa_coreAPI::setState( 'v', 'vid', $visitor_id, 'cookie', true ); + } + // set property on event object + $this->setGlobalEventProperty( 'visitor_id', $visitor_id ); + } + + private function setNumberPriorSessions( &$event ) { + // if check for nps value in vistor cookie. + $nps = owa_coreAPI::getStateParam('v', 'nps'); + + // if new session, increment visit count and persist to state store + if ( $this->getGlobalEventProperty('is_new_session' ) ) { + + // set value to 0 if not found. + if ( ! $nps ) { + + $nps = "0"; + + } else { + + $nps = $nps + 1; + } + + owa_coreAPI::setState('v', 'nps', $nps, 'cookie', true); + } + + // set property on the event object + $this->setGlobalEventProperty('nps', $nps); + } + + private function setFirstSessionTimestamp( &$event ) { + + $fsts = owa_coreAPI::getStateParam( 'v', 'fsts' ); + + if ( ! $fsts ) { + $fsts = $event->get('timestamp'); + owa_coreAPI::setState(owa_coreAPI::getSetting('base', 'visitor_param'), 'fsts', $fsts , 'cookie', true); + } + + $this->setGlobalEventProperty( 'fsts', $fsts ); + + // calc days since first session + $dsfs = round( ( $fsts - $event->get( 'timestamp' ) ) / ( 3600 * 24 ) ) ; + owa_coreAPI::setState(owa_coreAPI::getSetting('base', 'visitor_param'), 'dsfs', $dsfs , 'cookie', true); + $this->setGlobalEventProperty( 'dsfs', $dsfs ); + } + + private function setDaysSinceLastSession( &$event ) { + + owa_coreAPI::debug('setting days since last session.'); + $dsps = ''; + if ( $this->getGlobalEventProperty( 'is_new_session' ) ) { + owa_coreAPI::debug( 'timestamp: ' . $event->get( 'timestamp' ) ); + $last_req = $this->getGlobalEventProperty( 'last_req' ); + if ( ! $last_req ) { + $last_req = $event->get( 'timestamp' ); + } + owa_coreAPI::debug( 'last_req: ' . $last_req ); + $dsps = round( ( $event->get( 'timestamp' ) - $last_req ) / ( 3600*24 ) ); + owa_coreAPI::setState('s', 'dsps', $dsps , 'cookie', true); + } + + if ( ! $dsps ) { + $dsps = owa_coreAPI::getState( 's', 'dsps' ); + + if ( ! $dsps ) { + $dsps = 0; + } + } + + $this->setGlobalEventProperty( 'dsps', $dsps ); + } + + private function setSessionId( &$event ) { + + $is_new_session = $this->isNewSession( $event->get( 'timestamp' ), $this->getGlobalEventProperty( 'last_req' ) ); + if ( $is_new_session ) { + //set prior_session_id + $prior_session_id = owa_coreAPI::getStateParam('s', 'sid'); + if ( ! $prior_session_id ) { + $state_store_name = sprintf('%s_%s', owa_coreAPI::getSetting('base', 'site_session_param'), $this->site_id); + $prior_session_id = owa_coreAPI::getStateParam($state_store_name, 's'); + } + if ($prior_session_id) { + $this->setGlobalEventProperty( 'prior_session_id', $prior_session_id ); + } + + $this->resetSessionState(); + + $session_id = $event->getSiteSpecificGuid( $this->site_id ); + + //mark new session flag on current request + $this->setGlobalEventProperty( 'is_new_session', true ); + owa_coreAPI::setState( 's', 'sid', $session_id, 'cookie', true ); + + } else { + // Must be an active session so just pull the session id from the state store + $session_id = owa_coreAPI::getStateParam('s', 'sid'); + + // support for old style cookie + if ( ! $session_id ) { + $state_store_name = sprintf('%s_%s', owa_coreAPI::getSetting('base', 'site_session_param'), $this->site_id); + $session_id = owa_coreAPI::getStateParam($state_store_name, 's'); + + } + + // fail-safe just in case there is no session_id + if ( ! $session_id ) { + $session_id = $event->getSiteSpecificGuid( $this->site_id ); + //mark new session flag on current request + $this->setGlobalEventProperty( 'is_new_session', true ); + owa_coreAPI::debug('setting failsafe session id'); + } + } + + // set global event property + $this->setGlobalEventProperty( 'session_id', $session_id ); + // set sid state + owa_coreAPI::setState( 's', 'sid', $session_id, 'cookie', true ); + } + + private function setLastRequestTime( &$event ) { + + $last_req = owa_coreAPI::getStateParam('s', 'last_req'); + + // suppport for old style cookie + if ( ! $last_req ) { + $state_store_name = sprintf( '%s_%s', owa_coreAPI::getSetting( 'base', 'site_session_param' ), $this->site_id ); + $last_req = owa_coreAPI::getStateParam( $state_store_name, 'last_req' ); + } + // set property on event object + $this->setGlobalEventProperty( 'last_req', $last_req ); + owa_coreAPI::debug("setting last_req value of $last_req as global event property."); + // store new state value + owa_coreAPI::setState( 's', 'last_req', $event->get( 'timestamp' ), 'cookie', true ); + } + + /** + * Check to see if request is a new or active session + * + * @return boolean + */ + private function isNewSession($timestamp = '', $last_req = 0) { + + $is_new_session = false; + + if ( ! $timestamp ) { + $timestamp = time(); + } + + $time_since_lastreq = $timestamp - $last_req; + $len = owa_coreAPI::getSetting( 'base', 'session_length' ); + if ( $time_since_lastreq < $len ) { + owa_coreAPI::debug("This request is part of a active session."); + return false; + } else { + //NEW SESSION. prev session expired, because no requests since some time. + owa_coreAPI::debug("This request is the start of a new session. Prior session expired."); + return true; + } + } + + /** + * Logs tracking event from url params taken from request scope. + * Takes event type from url. + * + * @return unknown + */ + function logEventFromUrl($manage_state = false) { + + // keeps php executing even if the client closes the connection + ignore_user_abort(true); + $service = owa_coreAPI::serviceSingleton(); + $service->request->decodeRequestParams(); + $event = owa_coreAPI::supportClassFactory('base', 'event'); + $event->setEventType(owa_coreAPI::getRequestParam('event_type')); + $event->setProperties($service->request->getAllOwaParams()); + + // check for third party cookie mode. + $mode = owa_coreAPI::getRequestParam('thirdParty'); + if ( $mode ) { + return $this->trackEvent($event); + } else { + return owa_coreAPI::logEvent($event->getEventType(), $event); + } + } + + /** + * Logs tracking event + * + * This function fires a tracking event that will be processed and then dispatched + * + * @param object $event + * @return boolean + */ + public function trackEvent($event) { + + // do not track anything if user is in overlay mode + if (owa_coreAPI::getStateParam('overlay')) { + return false; + } + + $this->setGlobalEventProperty( 'HTTP_REFERER', owa_coreAPI::getServerParam('HTTP_REFERER') ); + + // needed by helper page tags function so it can append to first hit tag url + if (!$this->getSiteId()) { + $this->setSiteId($event->get('site_id')); + } + + if (!$this->getSiteId()) { + $this->setSiteId(owa_coreAPI::getRequestParam('site_id')); + } + + // set various state properties. + $this->manageState( $event ); + + $event = $this->setAllGlobalEventProperties( $event ); + + // send event to log API for processing. + return owa_coreAPI::logEvent($event->getEventType(), $event); + } + + public function setAllGlobalEventProperties( $event ) { + + if ( ! $event->get('site_id') ) { + $event->set( 'site_id', $this->getSiteId() ); + } + + // add custom variables to global properties if not there already + for ( $i=1; $i <= owa_coreAPI::getSetting('base', 'maxCustomVars'); $i++ ) { + $cv_param_name = 'cv' . $i; + $cv_value = ''; + + // if the custom var is not already a global property + if ( ! $this->getGlobalEventProperty( $cv_param_name ) ) { + // check to see if it exists + $cv_value = $this->getCustomVar( $i ); + // if so add it + if ( $cv_value ) { + $this->setGlobalEventProperty( $cv_param_name, $cv_value ); + } + } + } + + // merge global event properties + $event->setNewProperties( $this->global_event_properties ); + + return $event; + + } + + public function getAllEventProperties( $event ) { + + $event = $this->setAllGlobalEventProperties( $event ); + return $event->getProperties(); + } + + public function trackPageview($event = '') { + + if ($event) { + $event->setEventType('base.page_request'); + $this->pageview_event = $event; + } + return $this->trackEvent($this->pageview_event); + } + + public function trackAction($action_group = '', $action_name, $action_label = '', $numeric_value = 0) { + + $event = $this->makeEvent(); + $event->setEventType('track.action'); + $event->set('action_group', $action_group); + $event->set('action_name', $action_name); + $event->set('action_label', $action_label); + $event->set('numeric_value', $numeric_value); + $event->set('site_id', $this->getSiteId()); + return $this->trackEvent($event); + } + + /** + * Creates a ecommerce Transaction event + * + * Creates a parent commerce.transaction event + */ + public function addTransaction( + $order_id, + $order_source = '', + $total = 0, + $tax = 0, + $shipping = 0, + $gateway = '', + $country = '', + $state = '', + $city = '', + $page_url = '', + $session_id = '' + ) { + + $this->commerce_event = $this->makeEvent(); + $this->commerce_event->setEventType( 'ecommerce.transaction' ); + $this->commerce_event->set( 'ct_order_id', $order_id ); + $this->commerce_event->set( 'ct_order_source', $order_source ); + $this->commerce_event->set( 'ct_total', $total ); + $this->commerce_event->set( 'ct_tax', $tax ); + $this->commerce_event->set( 'ct_shipping', $shipping ); + $this->commerce_event->set( 'ct_gateway', $gateway ); + $this->commerce_event->set( 'page_url', $page_url ); + $this->commerce_event->set( 'ct_line_items', array() ); + $this->commerce_event->set( 'country', $country ); + $this->commerce_event->set( 'state', $state ); + $this->commerce_event->set( 'city', $city ); + if ( $session_id ) { + $this->commerce_event->set( 'original_session_id', $session_id ); + // tells the client to NOT manage state properties as we are + // going to look them up from the session later. + $this->commerce_event->set( 'is_state_set', true ); + } + } + + /** + * Adds a line item to a commerce transaction + * + * Creates and a commerce.line_item event and adds it to the parent transaction event + */ + public function addTransactionLineItem($order_id, $sku = '', $product_name = '', $category = '', $unit_price = 0, $quantity = 0) { + + if ( empty( $this->commerce_event ) ) { + $this->addTransaction('none set'); + } + + $li = array(); + $li['li_order_id'] = $order_id ; + $li['li_sku'] = $sku ; + $li['li_product_name'] = $product_name ; + $li['li_category'] = $category ; + $li['li_unit_price'] = $unit_price ; + $li['li_quantity'] = $quantity ; + + $items = $this->commerce_event->get( 'ct_line_items' ); + $items[] = $li; + $this->commerce_event->set( 'ct_line_items', $items ); + } + + /** + * tracks a commerce events + * + * Tracks a parent transaction event by sending it to the event queue + */ + public function trackTransaction() { + + if ( ! empty( $this->commerce_event ) ) { + $this->trackEvent( $this->commerce_event ); + $this->commerce_event = ''; + } + } + + public function createSiteId($value) { + + return md5($value); + } + + public function setCampaignNameKey( $key ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_params[ 'campaign' ] = $key; + owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); + } + + public function setCampaignMediumKey( $key ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_params[ 'medium' ] = $key; + owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); + } + + public function setCampaignSourceKey( $key ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_params[ 'source' ] = $key; + owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); + } + + public function setCampaignSearchTermsKey( $key ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_params[ 'search_terms' ] = $key; + owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); + } + + public function setCampaignAdKey( $key ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_params[ 'ad' ] = $key; + owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); + } + + public function setCampaignAdTypeKey( $key ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_params[ 'ad_type' ] = $key; + owa_coreAPI::setSetting('base', 'campaign_params', $campaign_params); + } + + public function setUserName( $value ) { + + $this->setGlobalEventProperty( 'user_name', $value ); + } + + function getCampaignProperties( $event ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + $campaign_properties = array(); + $campaign_state = array(); + $request = owa_coreAPI::getRequest(); + foreach ( $campaign_params as $k => $param ) { + //look for property on the event + $property = $event->get( $param ); + + // look for property on the request scope. + if ( ! $property ) { + $property = $request->getRequestParam( $param ); + } + if ( $property ) { + $campaign_properties[ $k ] = $property; + } + } + + // backfill values for incomplete param combos + + if (array_key_exists('ad_type', $campaign_properties) && !array_key_exists('ad', $campaign_properties)) { + $campaign_properties['ad'] = '(not set)'; + } + + if (array_key_exists('ad', $campaign_properties) && !array_key_exists('ad_type', $campaign_properties)) { + $campaign_properties['ad_type'] = '(not set)'; + } + + if (!empty($campaign_properties)) { + //$campaign_properties['ts'] = $event->get('timestamp'); + } + + owa_coreAPI::debug('campaign properties: '. print_r($campaign_properties, true)); + + return $campaign_properties; + } + + private function setCampaignSessionState( $properties ) { + + $campaign_params = owa_coreAPI::getSetting( 'base', 'campaign_params' ); + foreach ($campaign_params as $k => $v) { + + if (array_key_exists( $k, $properties ) ) { + + owa_coreAPI::setState( 's', $k, $properties[$k] ); + } + } + } + + function directAttributionModel( &$campaign_properties ) { + + // add new campaign info to existing campaign cookie. + if ( $campaign_properties ) { + + // get prior campaing touches from c cookie + $campaign_state = $this->getCampaignState(); + + // add new campaign into state array + $campaign_state[] = (object) $campaign_properties; + + // if more than x slice the first one off to make room + $count = count( $campaign_state ); + $max = owa_coreAPI::getSetting( 'base', 'max_prior_campaigns'); + if ($count > $max ) { + array_shift( $campaign_state ); + } + + // reset state + $this->setCampaignCookie($campaign_state); + + // set flag + $this->isTrafficAttributed = true; + + // persist state to session store + $this->setCampaignSessionState( $campaign_properties ); + } + + } + + function originalAttributionModel( &$campaign_properties ) { + + $campaign_state = $this->getCampaignState(); + // orignal touch was set previously. jus use that. + if (!empty($campaign_state)) { + // do nothing + // set the attributes from the first campaign touch + $campaign_properties = $campaign_state[0]; + $this->isTrafficAttributed = true; + + // no orginal touch, set one if it's a new campaign touch + } else { + + if (!empty($campaign_properties)) { + // add timestamp + //$campaign_properties['ts'] = $event->get('timestamp'); + owa_coreAPI::debug('Setting original Campaign attrbution.'); + $campaign_state[] = $campaign_properties; + // set cookie + $this->setCampaignCookie($campaign_state); + $this->isTrafficAttributed = true; + } + } + + // persist state to session store + $this->setCampaignSessionState( $campaign_properties ); + } + + function getCampaignState() { + + $campaign_state = owa_coreAPI::getState( 'c', 'attribs' ); + if ( ! $campaign_state ) { + + $campaign_state = array(); + } + + return $campaign_state; + } + + function setTrafficAttribution( &$event ) { + + // if not then look for individual campaign params on the request. + // this happens when the client is php and the params are on the url + $campaign_properties = $this->getCampaignProperties( $event ); + if ( $campaign_properties ) { + $campaign_properties['ts'] = $event->get('timestamp'); + } + + // choose attribution model. + $model = owa_coreAPI::getSetting('base', 'trafficAttributionMode'); + switch ( $model ) { + + case 'direct': + owa_coreAPI::debug( 'Applying "Direct" Traffic Attribution Model' ); + $this->directAttributionModel( $campaign_properties ); + break; + case 'original': + owa_coreAPI::debug( 'Applying "Original" Traffic Attribution Model' ); + $this->originalAttributionModel( $campaign_properties ); + break; + default: + owa_coreAPI::debug( 'Applying Default (Direct) Traffic Attribution Model' ); + $this->directAttributionModel( $campaign_properties ); + } + + // if one of the attribution methods attributes the traffic them + // set attribution properties on the event object + if ( $this->isTrafficAttributed ) { + + owa_coreAPI::debug( 'Attributing Traffic to: %s', print_r($campaign_properties, true ) ); + + } else { + // infer the attribution from the referer + // if the request is the start of a new session + if ( $this->getGlobalEventProperty( 'is_new_session' ) ) { + owa_coreAPI::debug( 'Infering traffic attribution.' ); + $this->inferTrafficAttribution(); + } + } + + // apply traffic attribution realted properties to events + // all properties should be set in the state store by this point. + $campaign_params = owa_coreAPI::getSetting('base', 'campaign_params'); + foreach( $campaign_params as $k => $v ) { + + $value = owa_coreAPI::getState( 's', $k ); + + if ( $value ) { + $this->setGlobalEventProperty( $k, $value ); + } + } + + // set sesion referer + $session_referer = owa_coreAPI::getState('s', 'referer'); + if ( $session_referer ) { + + $this->setGlobalEventProperty( 'session_referer', $session_referer ); + } + + // set campaign touches + $campaign_state = owa_coreAPI::getState('c', 'attribs'); + if ( $campaign_state ) { + + $this->setGlobalEventProperty( 'attribs', json_encode( $campaign_state )); + } + } + + private function inferTrafficAttribution() { + + $ref = owa_coreAPI::getServerParam('HTTP_REFERER'); + $medium = 'direct'; + $source = '(none)'; + $search_terms = '(none)'; + $session_referer = '(none)'; + + if ( $ref ) { + $uri = owa_lib::parse_url( $ref ); + + // check for external referer + $host = owa_coreAPI::getServerParam('HTTP_HOST'); + if ( $host != $uri['host'] ) { + + $medium = 'referral'; + $source = owa_lib::stripWwwFromDomain( $uri['host'] ); + $engine = $this->isRefererSearchEngine( $uri ); + $session_referer = $ref; + if ( $engine ) { + $medium = 'organic-search'; + $search_terms = $engine['t']; + } + } + } + + owa_coreAPI::setState('s', 'referer', $session_referer); + owa_coreAPI::setState('s', 'medium', $medium); + owa_coreAPI::setState('s', 'source', $source); + owa_coreAPI::setState('s', 'search_terms', $search_terms); + } + + private function isRefererSearchEngine( $uri ) { + + if ( isset( $uri['host'] ) ) { + $host = $uri['host']; + } else { + return; + } + + foreach ( $this->organicSearchEngines as $engine ) { + + $domain = $engine['d']; + $query_param = $engine['q']; + $term = ''; + + if ( isset ($uri['query_params'][$query_param] ) ) { + $term = $uri['query_params'][$query_param]; + } + + if ( strpos($host, $domain) ) { + owa_coreAPI::debug( 'Found search engine: %s with query param %s:, query term: %s', $domain, $query_param, $term); + + return array('d' => $domain, 'q' => $query_param, 't' => $term ); + } + } + } + + function setCampaignCookie($values) { + // reset state + owa_coreAPI::setState('c', 'attribs', $values); + } + + // sets cookies domain + function setCookieDomain($domain) { + + if (!empty($domain)) { + $c = owa_coreAPI::configSingleton(); + // sanitizes the domain + $c->setCookieDomain($domain); + } + } + + /** + * Set a custom variable + * + * @param slot int the identifying number for the custom variable. 1-5. + * @param name string the key of the custom variable. + * @param value string the value of the varible + * @param scope string the scope of the variable. can be page, session, or visitor + */ + public function setCustomVar( $slot, $name, $value, $scope = '' ) { + + $cv_param_name = 'cv' . $slot; + $cv_param_value = $name . '=' . $value; + + if ( strlen( $cv_param_value ) > 65 ) { + owa_coreAPI::debug('Custom variable name + value is too large. Must be less than 64 characters.'); + return; + } + + switch ( $scope ) { + + case 'session': + + // store in session cookie + owa_coreAPI::setState( 'b', $cv_param_name, $cv_param_value ); + owa_coreAPI::debug( 'just set custom var on session.' ); + break; + + case 'visitor': + + // store in visitor cookie + owa_coreAPI::setState( 'v', $cv_param_name, $cv_param_value ); + // remove slot from session level cookie + owa_coreAPI::clearState( 'b', $cv_param_name ); + break; + } + + $this->setGlobalEventProperty( $cv_param_name, $cv_param_value ); + } + + public function getCustomVar( $slot ) { + + $cv_param_name = 'cv' . $slot; + $cv = ''; + // check request/page level + $cv = $this->getGlobalEventProperty( $cv_param_name ); + //check session store + if ( ! $cv ) { + $cv = owa_coreAPI::getState( 'b', $cv_param_name ); + } + // check visitor store + if ( ! $cv ) { + $cv = owa_coreAPI::getState( 'v', $cv_param_name ); + } + + return $cv; + + } + + public function deleteCustomVar( $slot ) { + + $cv_param_name = 'cv' . $slot; + //clear session level + owa_coreAPI::clearState( 'b', $cv_param_name ); + //clear visitor level + owa_coreAPI::clearState( 'v', $cv_param_name ); + // clear page level + $this->deleteGlobalEventProperty( $cv_param_name ); + + owa_coreAPI::debug("Deleting custom variable named $cv_param_name in slot $slot."); + } + + private function resetSessionState() { + + $last_req = owa_coreAPI::getState( 's', 'last_req' ); + owa_coreAPI::clearState( 's' ); + owa_coreAPI::setState( 's', 'last_req', $last_req); + } + + public function addOrganicSearchEngine( $domain, $query_param, $prepend = '' ) { + + $engine = array('d' => $domain, 'q' => $query_param); + if ( $prepend) { + array_unshift($this->organicSearchEngines, $engine ); + } else { + $this->organicSearchEngines[] = $engine; + } + } } ?> diff --git a/modules/base/classes/column.php b/modules/base/classes/column.php index ab6682905..1a2a542b6 100644 --- a/modules/base/classes/column.php +++ b/modules/base/classes/column.php @@ -1,198 +1,198 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_dbColumn { - - var $name; - - var $value; - - var $data_type; - - var $foriegn_key; - - var $is_primary_key = false; - - var $auto_increment = false; - - var $is_unique = false; - - var $is_not_null = false; - - var $label; - - var $index; - - var $default_value; - - function __construct($name ='', $data_type = '') { - - if ($name) { - $this->setName($name); - } - - if ($data_type) { - $this->setDataType($data_type); - } - - } - - function get($name) { - - return $this->$name; - } - - function set($name, $value) { - - $this->$name = $value; - - return; - } - - function getValue() { - - return $this->value; - } - - function setValue($value) { - - $this->value = $value; - - return; - } - - function getDefinition() { - - $definition = ''; - - $definition .= $this->get('data_type'); - - // Check for auto increment - if ($this->get('auto_increment') == true): - $definition .= ' '.OWA_DTD_AUTO_INCREMENT; - endif; - - // Check for auto Not null - if ($this->get('is_not_null') == true): - $definition .= ' '.OWA_DTD_NOT_NULL; - endif; - - // Check for unique - if ($this->get('is_unique') == true): - $definition .= ' '.OWA_DTD_UNIQUE; - endif; - - // check for primary key - if ($this->get('is_primary_key') == true): - $definition .= ' '.OWA_DTD_PRIMARY_KEY; - //$definition .= sprintf(", INDEX (%s)", $this->get('name')); - endif; - - // check for index - if ($this->get('index') == true): - $definition .= sprintf(", INDEX (%s)", $this->get('name')); - endif; - - return $definition; - - } - - function setDataType($type) { - - $this->data_type = $type; - } - - function setDefaultValue($value) { - - $this->default_value = $value; - } - - function setPrimaryKey() { - - $this->is_primary_key = true; - } - - function setIndex() { - - $this->index = true; - } - - function setNotNull() { - - $this->is_not_null = true; - } - - function setUnique() { - - $this->is_unique = true; - } - - function setLabel($label) { - - $this->label = $label; - } - - function setForeignKey($entity, $column = 'id') { - - $this->foreign_key = array($entity, $column); - } - - function getForeignKey() { - - return $this->foreign_key; - } - - function isForeignKey() { - - if (!empty($this->foreign_key)) { - return true; - } else { - return false; - } - } - - function setAutoIncrement() { - - $this->auto_increment = true; - } - - function setName($name) { - - $this->name = $name; - } - - function getName() { - - return $this->name; - } - - } - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_dbColumn { + + var $name; + + var $value; + + var $data_type; + + var $foriegn_key; + + var $is_primary_key = false; + + var $auto_increment = false; + + var $is_unique = false; + + var $is_not_null = false; + + var $label; + + var $index; + + var $default_value; + + function __construct($name ='', $data_type = '') { + + if ($name) { + $this->setName($name); + } + + if ($data_type) { + $this->setDataType($data_type); + } + + } + + function get($name) { + + return $this->$name; + } + + function set($name, $value) { + + $this->$name = $value; + + return; + } + + function getValue() { + + return $this->value; + } + + function setValue($value) { + + $this->value = $value; + + return; + } + + function getDefinition() { + + $definition = ''; + + $definition .= $this->get('data_type'); + + // Check for auto increment + if ($this->get('auto_increment') == true): + $definition .= ' '.OWA_DTD_AUTO_INCREMENT; + endif; + + // Check for auto Not null + if ($this->get('is_not_null') == true): + $definition .= ' '.OWA_DTD_NOT_NULL; + endif; + + // Check for unique + if ($this->get('is_unique') == true): + $definition .= ' '.OWA_DTD_UNIQUE; + endif; + + // check for primary key + if ($this->get('is_primary_key') == true): + $definition .= ' '.OWA_DTD_PRIMARY_KEY; + //$definition .= sprintf(", INDEX (%s)", $this->get('name')); + endif; + + // check for index + if ($this->get('index') == true): + $definition .= sprintf(", INDEX (%s)", $this->get('name')); + endif; + + return $definition; + + } + + function setDataType($type) { + + $this->data_type = $type; + } + + function setDefaultValue($value) { + + $this->default_value = $value; + } + + function setPrimaryKey() { + + $this->is_primary_key = true; + } + + function setIndex() { + + $this->index = true; + } + + function setNotNull() { + + $this->is_not_null = true; + } + + function setUnique() { + + $this->is_unique = true; + } + + function setLabel($label) { + + $this->label = $label; + } + + function setForeignKey($entity, $column = 'id') { + + $this->foreign_key = array($entity, $column); + } + + function getForeignKey() { + + return $this->foreign_key; + } + + function isForeignKey() { + + if (!empty($this->foreign_key)) { + return true; + } else { + return false; + } + } + + function setAutoIncrement() { + + $this->auto_increment = true; + } + + function setName($name) { + + $this->name = $name; + } + + function getName() { + + return $this->name; + } + + } + ?> \ No newline at end of file diff --git a/modules/base/classes/daemon.php b/modules/base/classes/daemon.php index ba1fc9578..e9ac5b8f6 100644 --- a/modules/base/classes/daemon.php +++ b/modules/base/classes/daemon.php @@ -1,224 +1,224 @@ params = $this->getArgs(); - - if (isset($this->params['interval'])) { - $this->job_scheduling_interval = $this->params['interval']; - } - - if (isset($this->params['max_workers'])) { - $this->max_workers = $this->params['max_workers']; - } - - if (isset($this->params['pid_file_location'])) { - $this->pidFileLocation = $this->params['pid_file_location']; - } - - if (isset($this->params['uid'])) { - $this->userID = $this->params['uid']; - } - - if (isset($this->params['gid'])) { - $this->groupID = $this->params['gid']; - } - - if (isset($this->params['pid_file_location'])) { - $this->pidFileLocation = $this->params['pid_file_location']; - } - - $s = owa_coreAPI::serviceSingleton(); - $this->jobs = $s->getMap('backgound_jobs'); - - $this->eq = owa_coreAPI::getEventDispatch(); - - return parent::__construct(); - } - - function getArgs() { - - $params = array(); - // get params from the command line args - // $argv is a php super global variable - global $argv; - for ( $i=1; $i < count( $argv ); $i++ ) { - $it = explode("=", $argv[$i]); - $params[$it[0]] = $it[1]; - } - - return $params; - } - - function _logMessage($msg, $status = DLOG_NOTICE) { - - if ($status & DLOG_TO_CONSOLE) { - echo $msg."\n"; + + var $pids = array(); + var $params = array(); + var $max_workers = 5; + var $job_scheduling_interval = 30; + var $eq; + var $workerCountByJob = array(); + var $lastExecutionTimeByJob = array(); + var $jobsByPid = array(); + var $defaultMaxWorkersPerJob = 3; + var $jobs; + + function __construct() { + + $this->params = $this->getArgs(); + + if (isset($this->params['interval'])) { + $this->job_scheduling_interval = $this->params['interval']; + } + + if (isset($this->params['max_workers'])) { + $this->max_workers = $this->params['max_workers']; + } + + if (isset($this->params['pid_file_location'])) { + $this->pidFileLocation = $this->params['pid_file_location']; + } + + if (isset($this->params['uid'])) { + $this->userID = $this->params['uid']; + } + + if (isset($this->params['gid'])) { + $this->groupID = $this->params['gid']; + } + + if (isset($this->params['pid_file_location'])) { + $this->pidFileLocation = $this->params['pid_file_location']; + } + + $s = owa_coreAPI::serviceSingleton(); + $this->jobs = $s->getMap('backgound_jobs'); + + $this->eq = owa_coreAPI::getEventDispatch(); + + return parent::__construct(); + } + + function getArgs() { + + $params = array(); + // get params from the command line args + // $argv is a php super global variable + global $argv; + for ( $i=1; $i < count( $argv ); $i++ ) { + $it = explode("=", $argv[$i]); + $params[$it[0]] = $it[1]; + } + + return $params; + } + + function _logMessage($msg, $status = DLOG_NOTICE) { + + if ($status & DLOG_TO_CONSOLE) { + echo $msg."\n"; } - owa_coreAPI::notice("Daemon: $msg"); - } - - function isWorkerAvailable() { - - $active_workers = count( $this->pids ); - $available_workers = $this->max_workers - $active_workers; - if ( $available_workers >= 1 ) { - return true; - } else { - return false; - } - } - - function isAnotherWorkerAllowed($job_name, $job_max_workers = '') { - - if ( ! $job_max_workers ) { - $job_max_workers = $this->defaultMaxWorkersPerJob; - } - - if ( array_key_exists($job_name, $this->workerCountByJob ) ) { - if ( $this->workerCountByJob[$job_name] < $job_max_workers) { - owa_coreAPI::debug(sprintf( - "New worker processes is allowed for job: %s. %d of %d processes are active.", - $job_name, - $this->workerCountByJob[$job_name], $job_max_workers - )); - return true; - } else { - owa_coreAPI::debug(sprintf( - "New worker processes not allowed for job: %s. %d of %d processes are active.", - $job_name, - $this->workerCountByJob[$job_name], $job_max_workers - )); - return false; - } - } else { - owa_coreAPI::debug(sprintf( - "New worker processes is allowed for job: %s. %d of %d processes are active.", - $job_name, - $this->workerCountByJob[$job_name], $job_max_workers - )); - return true; - } - } - - function isTimeForJob($cron_tab, $last_execution_time) { - - $cron = new CronParser(); - $cron->calcLastRan($cron_tab); - $last_due = $cron->getLastRanUnix(); - - if ($last_due > $last_execution_time) { - return true; - } else { - return false; - } - } - - function getLastExecutionTime($job_name) { - - if ( array_key_exists( $job_name, $this->lastExecutionTimeByJob ) ) { - return $this->lastExecutionTimeByJob[$job_name]; - } else { - return 0; - } - } - - /** - * This function is happening in a while loop - */ - function _doTask() { - - if ( $this->isWorkerAvailable() ) { - - $jobs = $this->jobs; - - if ( $jobs ) { - $i = 0; - //for ($i = 0; $i < $available_workers; $i++) { - foreach ($jobs as $k => $job) { - - if ( $this->isAnotherWorkerAllowed( $job['name'], $job['max_processes'] ) && - $this->isTimeForJob( $job['cron_tab'], $this->getLastExecutionTime( $job['name'] ) ) ) { - // fork a new child - $pid = pcntl_fork(); - if ( ! $pid ) { - // this part is executed in the child - owa_coreAPI::debug( 'New child process executing job ' . print_r( $job, true ) ); - pcntl_exec( OWA_DIR.'cli.php', $job['cmd'] ); // takes an array of arguments - exit(); - } elseif ($pid == -1) { - // happens when something goes wrong and fork fails (handle errors here) - owa_coreAPI::debug( 'Could not fork new child' ); - } else { - // this part is executed in the parent - // We add pids to a global array, so that when we get a kill signal - // we tell the kids to flush and exit. - if ( array_key_exists( $k, $this->workerCountByJob ) ) { - $this->workerCountByJob[$k]++; - } else { - $this->workerCountByJob[$k] = 1; - $this->lastExecutionTimeByJob[$k] = time(); - $this->jobsByPid[$pid] = $k; - } - - $this->pids[] = $pid; - } - } - } - } - } - - // Collect any children which have exited on their own. pcntl_waitpid will - // return the PID that exited or 0 or ERROR - // WNOHANG means we won't sit here waiting if there's not a child ready - // for us to reap immediately - // -1 means any child - $dead_and_gone = pcntl_waitpid( -1, $status, WNOHANG ); - - while( $dead_and_gone > 0 ) { - // Remove the gone pid from the array - unset( $this->pids[array_search( $dead_and_gone, $this->pids )] ); - $past_job = $this->jobsByPid[$dead_and_gone]; - // decrement worker count - --$this->workerCountByJob[$past_job]; - unset($this->jobsByPid[$dead_and_gone]); - - // Look for another one - $dead_and_gone = pcntl_waitpid( -1, $status, WNOHANG); - } - - owa_coreAPI::debug(sprintf( - "Daemon Statistics -- pidsByJob: %s, workerCountByJob: %s, lastExecutionTimeByJob: %s", - print_r( $this->pidsByJob, true), - print_r( $this->workerCountByJob, true), - print_r( $this->lastExecutiontimeByJob, true) - )); - - // Sleep for some interval - sleep($this->job_scheduling_interval); - } + owa_coreAPI::notice("Daemon: $msg"); + } + + function isWorkerAvailable() { + + $active_workers = count( $this->pids ); + $available_workers = $this->max_workers - $active_workers; + if ( $available_workers >= 1 ) { + return true; + } else { + return false; + } + } + + function isAnotherWorkerAllowed($job_name, $job_max_workers = '') { + + if ( ! $job_max_workers ) { + $job_max_workers = $this->defaultMaxWorkersPerJob; + } + + if ( array_key_exists($job_name, $this->workerCountByJob ) ) { + if ( $this->workerCountByJob[$job_name] < $job_max_workers) { + owa_coreAPI::debug(sprintf( + "New worker processes is allowed for job: %s. %d of %d processes are active.", + $job_name, + $this->workerCountByJob[$job_name], $job_max_workers + )); + return true; + } else { + owa_coreAPI::debug(sprintf( + "New worker processes not allowed for job: %s. %d of %d processes are active.", + $job_name, + $this->workerCountByJob[$job_name], $job_max_workers + )); + return false; + } + } else { + owa_coreAPI::debug(sprintf( + "New worker processes is allowed for job: %s. %d of %d processes are active.", + $job_name, + $this->workerCountByJob[$job_name], $job_max_workers + )); + return true; + } + } + + function isTimeForJob($cron_tab, $last_execution_time) { + + $cron = new CronParser(); + $cron->calcLastRan($cron_tab); + $last_due = $cron->getLastRanUnix(); + + if ($last_due > $last_execution_time) { + return true; + } else { + return false; + } + } + + function getLastExecutionTime($job_name) { + + if ( array_key_exists( $job_name, $this->lastExecutionTimeByJob ) ) { + return $this->lastExecutionTimeByJob[$job_name]; + } else { + return 0; + } + } + + /** + * This function is happening in a while loop + */ + function _doTask() { + + if ( $this->isWorkerAvailable() ) { + + $jobs = $this->jobs; + + if ( $jobs ) { + $i = 0; + //for ($i = 0; $i < $available_workers; $i++) { + foreach ($jobs as $k => $job) { + + if ( $this->isAnotherWorkerAllowed( $job['name'], $job['max_processes'] ) && + $this->isTimeForJob( $job['cron_tab'], $this->getLastExecutionTime( $job['name'] ) ) ) { + // fork a new child + $pid = pcntl_fork(); + if ( ! $pid ) { + // this part is executed in the child + owa_coreAPI::debug( 'New child process executing job ' . print_r( $job, true ) ); + pcntl_exec( OWA_DIR.'cli.php', $job['cmd'] ); // takes an array of arguments + exit(); + } elseif ($pid == -1) { + // happens when something goes wrong and fork fails (handle errors here) + owa_coreAPI::debug( 'Could not fork new child' ); + } else { + // this part is executed in the parent + // We add pids to a global array, so that when we get a kill signal + // we tell the kids to flush and exit. + if ( array_key_exists( $k, $this->workerCountByJob ) ) { + $this->workerCountByJob[$k]++; + } else { + $this->workerCountByJob[$k] = 1; + $this->lastExecutionTimeByJob[$k] = time(); + $this->jobsByPid[$pid] = $k; + } + + $this->pids[] = $pid; + } + } + } + } + } + + // Collect any children which have exited on their own. pcntl_waitpid will + // return the PID that exited or 0 or ERROR + // WNOHANG means we won't sit here waiting if there's not a child ready + // for us to reap immediately + // -1 means any child + $dead_and_gone = pcntl_waitpid( -1, $status, WNOHANG ); + + while( $dead_and_gone > 0 ) { + // Remove the gone pid from the array + unset( $this->pids[array_search( $dead_and_gone, $this->pids )] ); + $past_job = $this->jobsByPid[$dead_and_gone]; + // decrement worker count + --$this->workerCountByJob[$past_job]; + unset($this->jobsByPid[$dead_and_gone]); + + // Look for another one + $dead_and_gone = pcntl_waitpid( -1, $status, WNOHANG); + } + + owa_coreAPI::debug(sprintf( + "Daemon Statistics -- pidsByJob: %s, workerCountByJob: %s, lastExecutionTimeByJob: %s", + print_r( $this->pidsByJob, true), + print_r( $this->workerCountByJob, true), + print_r( $this->lastExecutiontimeByJob, true) + )); + + // Sleep for some interval + sleep($this->job_scheduling_interval); + } } ?> diff --git a/modules/base/classes/date.php b/modules/base/classes/date.php index 0d43b8fc3..622ab9fdd 100644 --- a/modules/base/classes/date.php +++ b/modules/base/classes/date.php @@ -24,118 +24,118 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_date { - var $yyyymmdd; - var $timestamp; - var $label; - var $label_formal; - var $year; - var $month; - var $day; - var $is_leap_year; - var $day_of_week; - var $day_of_week_label; - var $day_of_year; - var $day_of_year_label; - var $week_of_year; - var $hour; - var $minute; - var $second; - var $microsecond; - var $meridiem; - var $num_days_in_month; - var $utc_offset; - - function __construct() { - - return; - } - - function set($date, $format = 'yyyymmdd') { - - switch ($format) { - - case 'yyyymmdd': - $this->yyyymmdd = $date; - list($this->year, $this->month, $this->day) = sscanf($date, "%4d%2d%2d"); - $this->timestamp = mktime(0, 0, 0, $this->month, $this->day, $this->year); - break; - - case 'timestamp': - $this->timestamp = $date; - $this->yyyymmdd = date('Ymd', $date); - list($this->year, $this->month, $this->day) = sscanf($this->yyyymmdd, "%4d%2d%2d"); - break; - - - } - - $this->utc_offset = date('Z', $this->timestamp); - $this->hour = date('H', $this->timestamp); - $this->minute = date('i', $this->timestamp); - $this->second = date('s', $this->timestamp); - $this->microsecond = date('u', $this->timestamp); - $this->meridiem = date('a', $this->timestamp); - $this->day_of_week = date('w', $this->timestamp); - $this->day_of_week_label = date('l', $this->timestamp); - $this->week_of_year = date('W', $this->timestamp); - $this->day_of_year = date('z', $this->timestamp); - $this->num_days_in_month = date('t', $this->timestamp); - $this->label = date('m/d/Y', $this->timestamp); - $this->label_formal = date('F jS Y', $this->timestamp); - } - - function get($name){ - - return $this->$name; - } - - function getDay() { - return $this->day; - } - - function getMonth() { - return $this->month; - } - - function getYear() { - return $this->year; - } - - function getLabel($format = '') { - - if (empty($format)) { - - $format = 'label'; - - } else { - - $format = 'label_'.$format; - } - - return $this->$format; - } - - function getYyyymmdd() { - - return $this->yyyymmdd; - } - - function getTimestamp() { - - return $this->timestamp; - } - - function getLocalTimestamp() { - - return $this->getTimestamp() + $this->utc_offset; - } + var $yyyymmdd; + var $timestamp; + var $label; + var $label_formal; + var $year; + var $month; + var $day; + var $is_leap_year; + var $day_of_week; + var $day_of_week_label; + var $day_of_year; + var $day_of_year_label; + var $week_of_year; + var $hour; + var $minute; + var $second; + var $microsecond; + var $meridiem; + var $num_days_in_month; + var $utc_offset; + + function __construct() { + + return; + } + + function set($date, $format = 'yyyymmdd') { + + switch ($format) { + + case 'yyyymmdd': + $this->yyyymmdd = $date; + list($this->year, $this->month, $this->day) = sscanf($date, "%4d%2d%2d"); + $this->timestamp = mktime(0, 0, 0, $this->month, $this->day, $this->year); + break; + + case 'timestamp': + $this->timestamp = $date; + $this->yyyymmdd = date('Ymd', $date); + list($this->year, $this->month, $this->day) = sscanf($this->yyyymmdd, "%4d%2d%2d"); + break; + + + } + + $this->utc_offset = date('Z', $this->timestamp); + $this->hour = date('H', $this->timestamp); + $this->minute = date('i', $this->timestamp); + $this->second = date('s', $this->timestamp); + $this->microsecond = date('u', $this->timestamp); + $this->meridiem = date('a', $this->timestamp); + $this->day_of_week = date('w', $this->timestamp); + $this->day_of_week_label = date('l', $this->timestamp); + $this->week_of_year = date('W', $this->timestamp); + $this->day_of_year = date('z', $this->timestamp); + $this->num_days_in_month = date('t', $this->timestamp); + $this->label = date('m/d/Y', $this->timestamp); + $this->label_formal = date('F jS Y', $this->timestamp); + } + + function get($name){ + + return $this->$name; + } + + function getDay() { + return $this->day; + } + + function getMonth() { + return $this->month; + } + + function getYear() { + return $this->year; + } + + function getLabel($format = '') { + + if (empty($format)) { + + $format = 'label'; + + } else { + + $format = 'label_'.$format; + } + + return $this->$format; + } + + function getYyyymmdd() { + + return $this->yyyymmdd; + } + + function getTimestamp() { + + return $this->timestamp; + } + + function getLocalTimestamp() { + + return $this->getTimestamp() + $this->utc_offset; + } } diff --git a/modules/base/classes/dbEventQueue.php b/modules/base/classes/dbEventQueue.php index 544493e19..ce795df32 100644 --- a/modules/base/classes/dbEventQueue.php +++ b/modules/base/classes/dbEventQueue.php @@ -17,7 +17,7 @@ // if ( ! class_exists( 'owa_eventQueue' ) ) { - require_once( OWA_BASE_CLASS_DIR.'eventQueue.php' ); + require_once( OWA_BASE_CLASS_DIR.'eventQueue.php' ); } /** * Database backed Event Queue Implementation @@ -27,176 +27,176 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_dbEventQueue extends owa_eventQueue { - - var $db; - var $items_per_fetch = 50; - - function __construct( $map = array() ) { - - return parent::__construct( $map ); - } - - function connect() { - - $this->db = owa_coreAPI::dbSingleton(); - owa_coreAPI::debug('Connected to event queue.'); - return true; - } - - function sendMessage( $event ) { - - $qi = owa_coreAPI::entityFactory('base.queue_item'); - - $qi->getByPk( 'id', $event->getGuid() ); - - if ( ! $qi->wasPersisted() ) { - - $qi->set( 'id', $event->getGuid() ); - $qi->set( 'insertion_timestamp', $this->makeTimestamp() ); - $qi->set( 'insertion_datestamp', $this->makeDatestamp() ); - } + + var $db; + var $items_per_fetch = 50; + + function __construct( $map = array() ) { + + return parent::__construct( $map ); + } + + function connect() { + + $this->db = owa_coreAPI::dbSingleton(); + owa_coreAPI::debug('Connected to event queue.'); + return true; + } + + function sendMessage( $event ) { + + $qi = owa_coreAPI::entityFactory('base.queue_item'); + + $qi->getByPk( 'id', $event->getGuid() ); + + if ( ! $qi->wasPersisted() ) { + + $qi->set( 'id', $event->getGuid() ); + $qi->set( 'insertion_timestamp', $this->makeTimestamp() ); + $qi->set( 'insertion_datestamp', $this->makeDatestamp() ); + } - $qi->set( 'event_type', $event->getEventType() ); - $qi->set( 'status', $event->getStatus() ); - $qi->set( 'priority', $this->determinPriority( $event->getEventType() ) ); - $qi->set( 'event', $this->prepareMessage( $event ) ); - $qi->set( 'failed_attempt_count' , $event->getReceiveCount() ); // need to rename this column to received count - $qi->set( 'last_error_msg', $event->getErrorMsg() ); - $qi->set( 'last_attempt_timestamp', $event->getLastReceiveTimestamp() ); - - // set do not receive before timestamp - $not_before = $event->getDoNotReceiveBeforeTimestamp(); - - // backwards compatability, should remove this soon. - if ( ! $not_before && $event->getReceiveCount() != 0 ) { - $not_before = $this->determineNextAttempt( $qi->get('event_type'), $event->getReceiveCount() ); - } - - if ( $not_before ) { - $qi->set( 'not_before_timestamp', $not_before ); - } - - $qi->save(); - } - - function receiveMessage() { - owa_coreAPI::debug('getting message'); - $msg = $this->getNextItem(); - - if ( $msg ) { - $event = $this->decodeMessage( $msg->get('event') ); - $event->wasReceived(); - // backwards compat. remove soon. - $event->setOldQueueId( $msg->get('id') ); - // incrment the count of times the event has been receieved from the queue. - // increment timesstamps of when last receieved - $event->wasReceived(); - - return $event; - } - } - - function deleteMessage( $id ) { - - return $this->markAsHandled( $id ); - } - - function markAsHandled( $item_id ) { - - $qi = owa_coreAPI::entityFactory('base.queue_item'); - $qi->load( $item_id ); - - if ( $qi->wasPersisted() ) { - $qi->set( 'status', 'handled' ); - $qi->set( 'handled_timestamp', $this->makeTimestamp() ); - $qi->save(); - } else { - owa_coreAPI::notice("Could not find/delete queue item id: $item_id"); - } - } - - function getNextItems($limit = '') { - - if ( ! $limit ) { - $limit = $this->items_per_fetch; - } - $this->db->select( '*' ); - $this->db->from( 'owa_queue_item' ); - $this->db->where( 'status', 'unhandled' ); - $this->db->where( 'not_before_timestamp', time(), '<' ); - $this->db->orderBy( 'insertion_timestamp' , 'ASC' ); - $this->db->limit( $limit ); - - $items = $this->db->getAllRows(); - - if ( $items ) { - $entities = array(); - foreach ( $items as $item ) { - $qi = owa_coreAPI::entityFactory( 'base.queue_item' ); - $qi->setProperties( $item ); - $entities[] = $qi; - } - - if ( $limit > 1 ) { - return $entities; - } else { - return $entities[0]; - } - } - } - - function flushHandledEvents() { - - $this->db->deleteFrom( 'owa_queue_item' ); - $this->db->where( 'status' , 'handled'); - $ret = $this->db->executeQuery(); - return $this->db->getAffectedRows(); - } - - /** - * Prune the event archive - * @todo make an event archive table - * @todo modify flushHandledEvents to move handled events to an archive. - */ - function pruneArchive( $interval ) { - - return true; - } - - function getNextItem() { - - return $this->getNextItems(1); - } - - function determineNextAttempt($event_type, $failed_count) { - - return $this->makeTimeStamp() +30; - } - - function makeTimestamp() { - - return time(); - } - - // safe for mysql timestamp column type - function makeDatestamp($time = '') { - - if ( ! $time ) { - $time = time(); - } - - return gmdate("Y-m-d H:i:s", $time); - } - - function determinPriority($event_type) { - - return 99; - } + $qi->set( 'event_type', $event->getEventType() ); + $qi->set( 'status', $event->getStatus() ); + $qi->set( 'priority', $this->determinPriority( $event->getEventType() ) ); + $qi->set( 'event', $this->prepareMessage( $event ) ); + $qi->set( 'failed_attempt_count' , $event->getReceiveCount() ); // need to rename this column to received count + $qi->set( 'last_error_msg', $event->getErrorMsg() ); + $qi->set( 'last_attempt_timestamp', $event->getLastReceiveTimestamp() ); + + // set do not receive before timestamp + $not_before = $event->getDoNotReceiveBeforeTimestamp(); + + // backwards compatability, should remove this soon. + if ( ! $not_before && $event->getReceiveCount() != 0 ) { + $not_before = $this->determineNextAttempt( $qi->get('event_type'), $event->getReceiveCount() ); + } + + if ( $not_before ) { + $qi->set( 'not_before_timestamp', $not_before ); + } + + $qi->save(); + } + + function receiveMessage() { + owa_coreAPI::debug('getting message'); + $msg = $this->getNextItem(); + + if ( $msg ) { + $event = $this->decodeMessage( $msg->get('event') ); + $event->wasReceived(); + // backwards compat. remove soon. + $event->setOldQueueId( $msg->get('id') ); + // incrment the count of times the event has been receieved from the queue. + // increment timesstamps of when last receieved + $event->wasReceived(); + + return $event; + } + } + + function deleteMessage( $id ) { + + return $this->markAsHandled( $id ); + } + + function markAsHandled( $item_id ) { + + $qi = owa_coreAPI::entityFactory('base.queue_item'); + $qi->load( $item_id ); + + if ( $qi->wasPersisted() ) { + $qi->set( 'status', 'handled' ); + $qi->set( 'handled_timestamp', $this->makeTimestamp() ); + $qi->save(); + } else { + owa_coreAPI::notice("Could not find/delete queue item id: $item_id"); + } + } + + function getNextItems($limit = '') { + + if ( ! $limit ) { + $limit = $this->items_per_fetch; + } + $this->db->select( '*' ); + $this->db->from( 'owa_queue_item' ); + $this->db->where( 'status', 'unhandled' ); + $this->db->where( 'not_before_timestamp', time(), '<' ); + $this->db->orderBy( 'insertion_timestamp' , 'ASC' ); + $this->db->limit( $limit ); + + $items = $this->db->getAllRows(); + + if ( $items ) { + $entities = array(); + foreach ( $items as $item ) { + $qi = owa_coreAPI::entityFactory( 'base.queue_item' ); + $qi->setProperties( $item ); + $entities[] = $qi; + } + + if ( $limit > 1 ) { + return $entities; + } else { + return $entities[0]; + } + } + } + + function flushHandledEvents() { + + $this->db->deleteFrom( 'owa_queue_item' ); + $this->db->where( 'status' , 'handled'); + $ret = $this->db->executeQuery(); + return $this->db->getAffectedRows(); + } + + /** + * Prune the event archive + * @todo make an event archive table + * @todo modify flushHandledEvents to move handled events to an archive. + */ + function pruneArchive( $interval ) { + + return true; + } + + function getNextItem() { + + return $this->getNextItems(1); + } + + function determineNextAttempt($event_type, $failed_count) { + + return $this->makeTimeStamp() +30; + } + + function makeTimestamp() { + + return time(); + } + + // safe for mysql timestamp column type + function makeDatestamp($time = '') { + + if ( ! $time ) { + $time = time(); + } + + return gmdate("Y-m-d H:i:s", $time); + } + + function determinPriority($event_type) { + + return 99; + } } ?> \ No newline at end of file diff --git a/modules/base/classes/error.php b/modules/base/classes/error.php index fa1040bfe..3fad57e6b 100644 --- a/modules/base/classes/error.php +++ b/modules/base/classes/error.php @@ -1,333 +1,333 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_error { - - const OWA_LOG_ALL = 0; - const OWA_LOG_DEBUG = 2; - const OWA_LOG_INFO = 4; - const OWA_LOG_NOTICE = 6; - const OWA_LOG_WARNING = 8; - const OWA_LOG_ERR = 10; - const OWA_LOG_CRIT = 12; - const OWA_LOG_ALERT = 14; - const OWA_LOG_EMERG = 16; - - /** - * logger instances - * - * @var array - */ - - var $loggers = array(); - /** - * Buffered Msgs - * - * @var array - */ - var $bmsgs; - - var $hasChildren = false; - - var $init = false; - - var $c; - - /** - * Constructor - * - */ - function __construct() { - - } - - function __destruct() { - - } - - // This is called by a client after the owas global config object has been created. - public function setHandler($type) { - - switch ($type) { - case "development": - $this->createDevelopmentHandler(); - break; - case "production": - $this->createProductionHandler(); - break; - default: - $this->createProductionHandler(); - } - - $this->init = true; - $this->logBufferedMsgs(); - } - - function createDevelopmentHandler() { - - // set log level to debug - owa_coreAPI::setSetting('base', 'error_log_level', self::OWA_LOG_DEBUG ); - // make file logger - $this->make_file_logger(); - // if the CLI is in use, makea console logger. - if ( defined('OWA_CLI') ) { - - $this->make_console_logger(); - } - - - $this->logPhpErrors(); - - set_exception_handler( array($this, 'logException') ); - - } - - function createProductionHandler() { - - // if the level is not changes from the defaul, set log level to notices and above - if (owa_coreAPI::getSetting( 'base', 'error_log_level') < 1 ) { - - owa_coreAPI::setSetting('base', 'error_log_level', self::OWA_LOG_NOTICE ); - } - // make file logger - $this->make_file_logger(); - // if the CLI is in use, makea console logger. - if ( defined('OWA_CLI') ) { - - $this->make_console_logger(); - } - } - - - function debug($message) { - - return $this->log($message, self::OWA_LOG_DEBUG); - } - - function info($message) { - - return $this->log($message, self::OWA_LOG_INFO); - } - - function notice($message) { - - return $this->log($message, self::OWA_LOG_NOTICE); - } - - function warning($message) { - - return $this->log($message, self::OWA_LOG_WARNING); - } - - function err($message) { - - return $this->log($message, self::OWA_LOG_ERR); - } - - function crit($message) { - - return $this->log($message, self::OWA_LOG_CRIT); - } - - function alert($message) { - - return $this->log($message, self::OWA_LOG_ALERT); - } - - function emerg($message) { - - return $this->log($message, self::OWA_LOG_EMERG); - } - - function log( $err, $priority = 0 ) { - - - if ( $this->init) { - // log to normal loggers - return $this->logMsg($err, $priority); - - } else { - // buffer msgs untill the global config object has been loaded - // and a proper logger can be setup - return $this->bufferMsg($err, $priority); - } - } - - function bufferMsg($err, $priority) { - - $this->bmsgs[] = array('error' => $err, 'priority' => $priority); - return true; - } - - function logBufferedMsgs() { - - if (!empty($this->bmsgs)) { - - foreach($this->bmsgs as $msg) { - - $this->log($msg['error'], $msg['priority']); - } - - $this->bmsgs = null; - } - } - - /** - * Builds a console logger - * - */ - function make_console_logger() { - - $conf = array('name' => 'console_log'); - $this->loggers['console'] = owa_coreAPI::supportClassFactory( 'base', 'logConsole', $conf ); - } - - /** - * Builds a logger that writes to a file. - * - */ - function make_file_logger() { - - $path = owa_coreAPI::getSetting('base', 'error_log_file'); - //instantiate a a log file - $conf = array('name' => 'debug_log', 'file_path' => $path); - $this->loggers['file'] = owa_coreAPI::supportClassFactory( 'base', 'logFile', $conf ); - } - - function logPhpErrors() { - - error_reporting( E_ALL ); - ini_set('display_errors', 'On'); - set_error_handler( array( $this, "handlePhpError" ) ); - ini_set("log_errors", 1); - ini_set("error_log", owa_coreAPI::getSetting('base', 'error_log_file') ); - } - - /** - * Alternative error handler for PHP specific errors. - * - * @param string $errno - * @param string $errmsg - * @param string $filename - * @param string $linenum - * @param string $vars - */ - function handlePhpError($errno = null, $errmsg, $filename, $linenum, $vars) { - - $dt = date("Y-m-d H:i:s (T)"); - - // set of errors for which a var trace will be saved - //$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_STRICT); - - $err = "\n"; - $err .= "\t" . $dt . "\n"; - $err .= "\t" . $errno . "\n"; - $err .= "\t" . $errmsg . "\n"; - $err .= "\t" . $filename . "\n"; - $err .= "\t" . $linenum . "\n"; - - //if (in_array($errno, $user_errors)) { - // $err .= "\t" . wddx_serialize_value($vars, "Variables") . "\n"; - //} - - $err .= "\n\n"; - - $this->debug( $err ); - } - - function logMsg( $msg, $priority ) { - - if ( is_object( $msg ) || is_array( $msg ) ) { - - $msg = print_r( $msg, true ); - } - - // check error priority before logging. - if ( owa_coreAPI::getSetting('base', 'error_log_level') <= $priority ) { - - $dt = date("H:i:s Y-m-d"); - $pid = getmypid(); - foreach ( $this->loggers as $logger ) { - - $message = sprintf("%s %s [%s] %s \n", $dt, $pid, $logger->name, $msg); - $logger->append( $message ); - } - } - } - - function backtrace() { - - $dbgTrace = debug_backtrace(); - $bt = array(); - foreach($dbgTrace as $dbgIndex => $dbgInfo) { - - $bt[$dbgIndex] = array('file' => $dbgInfo['file'], - 'line' => $dbgInfo['line'], - 'function' => $dbgInfo['function'], - 'args' => $dbgInfo['args']); - } - - return $bt; - - } - - function logException($exception) { - - $msg = $exception->getMessage() . ' // '.$exception->getTraceAsString(); - if (defined('OWA_MAIL_EXCEPTIONS')) { - $this->mailErrorMsg( $msg, 'Uncaught Exception' ); - } - - $this->log( $msg ); - } - - function mailErrorMsg( $msg, $subject ) { - - $body = 'Error Message: '. $msg . "\n"; - $body .= "POST: ". print_r($_POST, true) . "\n"; - $body .= "GET: ". print_r($_GET, true) . "\n"; - $body .= "Request: ". print_r($_REQUEST, true) . "\n"; - $body .= "Server: ". print_r($_SERVER, true) . "\n"; - $body .= "PID: ". getmypid() . "\n"; - - if ( isset( $_SERVER['SERVER_NAME'] ) ) { - - $server = $_SERVER['SERVER_NAME']; - } else { - - $server = __FILE__; - } - $conf = array('subject' => $subject . ' on '. $server, 'from' => 'OWA Error-logger', 'name' => 'exceptions_log'); - $logger = owa_coreAPI::supportClassFactory('base', 'logEmail', $conf); - $logger->log($body); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_error { + + const OWA_LOG_ALL = 0; + const OWA_LOG_DEBUG = 2; + const OWA_LOG_INFO = 4; + const OWA_LOG_NOTICE = 6; + const OWA_LOG_WARNING = 8; + const OWA_LOG_ERR = 10; + const OWA_LOG_CRIT = 12; + const OWA_LOG_ALERT = 14; + const OWA_LOG_EMERG = 16; + + /** + * logger instances + * + * @var array + */ + + var $loggers = array(); + /** + * Buffered Msgs + * + * @var array + */ + var $bmsgs; + + var $hasChildren = false; + + var $init = false; + + var $c; + + /** + * Constructor + * + */ + function __construct() { + + } + + function __destruct() { + + } + + // This is called by a client after the owas global config object has been created. + public function setHandler($type) { + + switch ($type) { + case "development": + $this->createDevelopmentHandler(); + break; + case "production": + $this->createProductionHandler(); + break; + default: + $this->createProductionHandler(); + } + + $this->init = true; + $this->logBufferedMsgs(); + } + + function createDevelopmentHandler() { + + // set log level to debug + owa_coreAPI::setSetting('base', 'error_log_level', self::OWA_LOG_DEBUG ); + // make file logger + $this->make_file_logger(); + // if the CLI is in use, makea console logger. + if ( defined('OWA_CLI') ) { + + $this->make_console_logger(); + } + + + $this->logPhpErrors(); + + set_exception_handler( array($this, 'logException') ); + + } + + function createProductionHandler() { + + // if the level is not changes from the defaul, set log level to notices and above + if (owa_coreAPI::getSetting( 'base', 'error_log_level') < 1 ) { + + owa_coreAPI::setSetting('base', 'error_log_level', self::OWA_LOG_NOTICE ); + } + // make file logger + $this->make_file_logger(); + // if the CLI is in use, makea console logger. + if ( defined('OWA_CLI') ) { + + $this->make_console_logger(); + } + } + + + function debug($message) { + + return $this->log($message, self::OWA_LOG_DEBUG); + } + + function info($message) { + + return $this->log($message, self::OWA_LOG_INFO); + } + + function notice($message) { + + return $this->log($message, self::OWA_LOG_NOTICE); + } + + function warning($message) { + + return $this->log($message, self::OWA_LOG_WARNING); + } + + function err($message) { + + return $this->log($message, self::OWA_LOG_ERR); + } + + function crit($message) { + + return $this->log($message, self::OWA_LOG_CRIT); + } + + function alert($message) { + + return $this->log($message, self::OWA_LOG_ALERT); + } + + function emerg($message) { + + return $this->log($message, self::OWA_LOG_EMERG); + } + + function log( $err, $priority = 0 ) { + + + if ( $this->init) { + // log to normal loggers + return $this->logMsg($err, $priority); + + } else { + // buffer msgs untill the global config object has been loaded + // and a proper logger can be setup + return $this->bufferMsg($err, $priority); + } + } + + function bufferMsg($err, $priority) { + + $this->bmsgs[] = array('error' => $err, 'priority' => $priority); + return true; + } + + function logBufferedMsgs() { + + if (!empty($this->bmsgs)) { + + foreach($this->bmsgs as $msg) { + + $this->log($msg['error'], $msg['priority']); + } + + $this->bmsgs = null; + } + } + + /** + * Builds a console logger + * + */ + function make_console_logger() { + + $conf = array('name' => 'console_log'); + $this->loggers['console'] = owa_coreAPI::supportClassFactory( 'base', 'logConsole', $conf ); + } + + /** + * Builds a logger that writes to a file. + * + */ + function make_file_logger() { + + $path = owa_coreAPI::getSetting('base', 'error_log_file'); + //instantiate a a log file + $conf = array('name' => 'debug_log', 'file_path' => $path); + $this->loggers['file'] = owa_coreAPI::supportClassFactory( 'base', 'logFile', $conf ); + } + + function logPhpErrors() { + + error_reporting( E_ALL ); + ini_set('display_errors', 'On'); + set_error_handler( array( $this, "handlePhpError" ) ); + ini_set("log_errors", 1); + ini_set("error_log", owa_coreAPI::getSetting('base', 'error_log_file') ); + } + + /** + * Alternative error handler for PHP specific errors. + * + * @param string $errno + * @param string $errmsg + * @param string $filename + * @param string $linenum + * @param string $vars + */ + function handlePhpError($errno = null, $errmsg, $filename, $linenum, $vars) { + + $dt = date("Y-m-d H:i:s (T)"); + + // set of errors for which a var trace will be saved + //$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_STRICT); + + $err = "\n"; + $err .= "\t" . $dt . "\n"; + $err .= "\t" . $errno . "\n"; + $err .= "\t" . $errmsg . "\n"; + $err .= "\t" . $filename . "\n"; + $err .= "\t" . $linenum . "\n"; + + //if (in_array($errno, $user_errors)) { + // $err .= "\t" . wddx_serialize_value($vars, "Variables") . "\n"; + //} + + $err .= "\n\n"; + + $this->debug( $err ); + } + + function logMsg( $msg, $priority ) { + + if ( is_object( $msg ) || is_array( $msg ) ) { + + $msg = print_r( $msg, true ); + } + + // check error priority before logging. + if ( owa_coreAPI::getSetting('base', 'error_log_level') <= $priority ) { + + $dt = date("H:i:s Y-m-d"); + $pid = getmypid(); + foreach ( $this->loggers as $logger ) { + + $message = sprintf("%s %s [%s] %s \n", $dt, $pid, $logger->name, $msg); + $logger->append( $message ); + } + } + } + + function backtrace() { + + $dbgTrace = debug_backtrace(); + $bt = array(); + foreach($dbgTrace as $dbgIndex => $dbgInfo) { + + $bt[$dbgIndex] = array('file' => $dbgInfo['file'], + 'line' => $dbgInfo['line'], + 'function' => $dbgInfo['function'], + 'args' => $dbgInfo['args']); + } + + return $bt; + + } + + function logException($exception) { + + $msg = $exception->getMessage() . ' // '.$exception->getTraceAsString(); + if (defined('OWA_MAIL_EXCEPTIONS')) { + $this->mailErrorMsg( $msg, 'Uncaught Exception' ); + } + + $this->log( $msg ); + } + + function mailErrorMsg( $msg, $subject ) { + + $body = 'Error Message: '. $msg . "\n"; + $body .= "POST: ". print_r($_POST, true) . "\n"; + $body .= "GET: ". print_r($_GET, true) . "\n"; + $body .= "Request: ". print_r($_REQUEST, true) . "\n"; + $body .= "Server: ". print_r($_SERVER, true) . "\n"; + $body .= "PID: ". getmypid() . "\n"; + + if ( isset( $_SERVER['SERVER_NAME'] ) ) { + + $server = $_SERVER['SERVER_NAME']; + } else { + + $server = __FILE__; + } + $conf = array('subject' => $subject . ' on '. $server, 'from' => 'OWA Error-logger', 'name' => 'exceptions_log'); + $logger = owa_coreAPI::supportClassFactory('base', 'logEmail', $conf); + $logger->log($body); + } +} + ?> \ No newline at end of file diff --git a/modules/base/classes/event.php b/modules/base/classes/event.php index 21d3bf808..bd6dcedcc 100644 --- a/modules/base/classes/event.php +++ b/modules/base/classes/event.php @@ -1,472 +1,472 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_event { - - /** - * Event Properties - * - * @var array - */ - var $properties = array(); - - /** - * State - * - * @var string - */ - //var $state; - - var $eventType; - - /** - * Time since last request. - * - * Used to tell if a new session should be created. - * - * @var integer $time_since_lastreq - */ - var $time_since_lastreq; - - /** - * Event guid - * - * @var string - */ - var $guid; - - /** - * Creation Timestamp in UNIX EPOC UTC - * - * @var int - */ - var $timestamp; - - /** - * Last error msg set by handler - * - * @var string - */ - var $last_error_msg; - - /** - * Number of times event was received from message quque - * - * @var integer - */ - var $receive_count = 0; - - /** - * Timestamp of last receipt from message queue - * - * @var string - */ - var $last_receive_timestamp; - - /** - * Timestamp of first receipt from message queue - * - * @var string - */ - var $first_receive_timestamp; - - /** - * Timestamp not to handled event before - * - * @var string - */ - var $do_not_receive_before_timestamp; - - var $status; - - // backwards compat. remove soon. - var $old_queue_id; - - const handled = 'handled'; - const unhandled = 'unhandled'; - const broken = 'broken'; - - /** - * Constructor - * @access public - */ - function __construct() { - - // Set GUID for event - $this->guid = $this->set_guid(); - $this->timestamp = time(); - //needed? - $this->set('guid', $this->guid); - $this->set('timestamp', $this->timestamp ); - $this->status = self::unhandled; - } - - function setStatusAsHandled() { - - $this->status = self::handled; - //clear any error - $this->last_error_msg = ''; - } - - function setStatusAsBroken() { - - $this->status = self::broken; - } - - function getTimestamp() { - - return $this->timestamp; - } - - function set($name, $value) { - - $this->properties[$name] = $value; - } - - function get($name) { - - if(array_key_exists($name, $this->properties)) { - //print_r($this->properties[$name]); - return $this->properties[$name]; - } else { - return false; - } - } - - /** - * removes a property - */ - function delete( $name ) { - - if (array_key_exists( $name, $this->properties ) ) { - - unset( $this->properties[ $name ] ); - } - } - - /** - * Sets time related event properties - * - * @param integer $timestamp - */ - function setTime($timestamp = null) { - - if ( $timestamp ) { - $this->set('timestamp', $timestamp); - } else { - $timestamp = $this->getTimestamp(); - } - - $this->set('timestamp', $timestamp); - $this->set('year', date("Y", $timestamp)); - $this->set('month', date("Ym", $timestamp)); - $this->set('day', date("d", $timestamp)); - $this->set('yyyymmdd', date("Ymd", $timestamp)); - $this->set('dayofweek', date("D", $timestamp)); - $this->set('dayofyear', date("z", $timestamp)); - $this->set('weekofyear', date("W", $timestamp)); - $this->set('hour', date("G", $timestamp)); - $this->set('minute', date("i", $timestamp)); - $this->set('second', date("s", $timestamp)); - - //epoc time - list($msec, $sec) = explode(" ", microtime()); - $this->set('sec', $sec); - $this->set('msec', $msec); - - } - - function setCookieDomain($domain) { - - $this->properties['cookie_domain'] = $domain; - } - - /** - * Determines the time since the last request from this borwser - * - * @access private - * @return integer - */ - function timeSinceLastRequest() { - - return ($this->get('timestamp') - $this->get('last_req')); - } - - /** - * Applies calling application specific properties to request - * - * @access private - * @param array $properties - */ - function setProperties($properties = null) { - - if(!empty($properties)) { - - if (empty($this->properties)) { - $this->properties = $properties; - } else { - $this->properties = array_merge($this->properties, $properties); - } - } - } - - /** - * Adds new properties to the eventt without overwriting values - * for properties that are already set. - * - * @param array $properties - */ - function setNewProperties( $properties = array() ) { - - $this->properties = array_merge($properties, $this->properties); - - } - - /** - * Exports Event Class variables - * - * @return array - */ - function export() { - - return get_object_vars( $this ); - } - - /** - * Loads Event class variables from an array - * - * @param array $properties - */ - function loadFromArray ( $vars ) { - - $has = get_object_vars( $this ); - - foreach ($has as $name => $oldValue ) { - - if ( isset( $vars[$name] ) ) { - - $this->$name = $vars[ $name ]; - } - } - } - - function replaceProperties($properties) { - - $this->properties = $properties; - } - - /** - * Create guid from process id - * - * @return integer - * @access private - */ - function set_guid() { - - return owa_lib::generateRandomUid(); - } - - /** - * Create guid from string - * - * @param string $string - * @return integer - * @access private - */ - function set_string_guid($string) { - - return crc32(strtolower($string)); - - } - - /** - * Attempts to make a unique ID out of http request variables. - * This should only be used when storing state in a cookie is impossible. - * - * @return integer - */ - function setEnvGUID() { - - return crc32( $this->get('ua') . $this->get('ip_address') ); - - } - - function setSiteSessionState($site_id, $name, $value, $store_type = 'cookie') { - - $store_name = owa_coreAPI::getSetting('base', 'site_session_param').'_'.$site_id; - return owa_coreAPI::setState($store_name, $name, $value, $store_type, true); - } - - function deleteSiteSessionState($site_id, $store_type = 'cookie') { - - $store_name = owa_coreAPI::getSetting('base', 'site_session_param').'_'.$site_id; - return owa_coreAPI::clearState($store_name); - } - - function getProperties() { - - return $this->properties; - } - - function getEventType() { - - if (!empty($this->eventType)) { - return $this->eventType; - } elseif ($this->get('event_type')) { - return $this->get('event_type'); - } else { - - return 'unknown_event_type'; - } - } - - function setEventType($value) { - $this->eventType = $value; - } - - function cleanProperties() { - - return $this->setProperties(owa_lib::inputFilter($this->getProperties())); - } - - function setPageTitle($value) { - - $this->set('page_title', $value); - } - - function setSiteId($value) { - - $this->set('siteId', $value); - $this->set('site_id', $value); - } - - function getSiteId() { - - if ( $this->get('siteId') ) { - return $this->get('siteId'); - } else { - return $this->get('site_id'); - } - - - } - - function setPageType($value) { - - $this->set('page_type', $value); - } - - function getGuid() { - - return $this->guid; - } - - function getSiteSpecificGuid($site_id) { - - return owa_lib::generateRandomUid(); - } - - function getStatus() { - - return $this->status; - } - - function setDoNotReceiveBeforeTimestamp( $time ) { - - $this->do_not_receive_before_timestamp = $time; - } - - function wasReceived() { - - $time = time(); - - $this->last_receive_timestamp = $time; - - if ( $this->receive_count === 0 ) { - - $this->first_receive_timestamp = $time; - } - - $this->incrementReceiveCount(); - } - - function incrementReceiveCount() { - - $this->receive_count++; - } - - function getReceiveCount() { - - return $this->receive_count; - } - - function setErrorMeg( $error_msg ) { - - $this->last_error_msg = $error_msg; - } - - function getErrorMsg() { - - return $this->last_error_msg; - } - - function getLastReceiveTimestamp() { - - return $this->last_receive_timestamp; - } - - function getDoNotReceiveBeforeTimestamp() { - - return $this->do_not_receive_before_timestamp; - } - - // backwards compat for dbEventQueue. remove_soon. - function setOldQueueId( $id ) { - - if ( $id != $this->getGuid() ) { - - $this->old_queue_id = $id; - } - } - - function getQueueGuid() { - - if ( $this->old_queue_id ) { - - return $this->old_queue_id; - - } else { - - return $this->getGuid(); - } - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_event { + + /** + * Event Properties + * + * @var array + */ + var $properties = array(); + + /** + * State + * + * @var string + */ + //var $state; + + var $eventType; + + /** + * Time since last request. + * + * Used to tell if a new session should be created. + * + * @var integer $time_since_lastreq + */ + var $time_since_lastreq; + + /** + * Event guid + * + * @var string + */ + var $guid; + + /** + * Creation Timestamp in UNIX EPOC UTC + * + * @var int + */ + var $timestamp; + + /** + * Last error msg set by handler + * + * @var string + */ + var $last_error_msg; + + /** + * Number of times event was received from message quque + * + * @var integer + */ + var $receive_count = 0; + + /** + * Timestamp of last receipt from message queue + * + * @var string + */ + var $last_receive_timestamp; + + /** + * Timestamp of first receipt from message queue + * + * @var string + */ + var $first_receive_timestamp; + + /** + * Timestamp not to handled event before + * + * @var string + */ + var $do_not_receive_before_timestamp; + + var $status; + + // backwards compat. remove soon. + var $old_queue_id; + + const handled = 'handled'; + const unhandled = 'unhandled'; + const broken = 'broken'; + + /** + * Constructor + * @access public + */ + function __construct() { + + // Set GUID for event + $this->guid = $this->set_guid(); + $this->timestamp = time(); + //needed? + $this->set('guid', $this->guid); + $this->set('timestamp', $this->timestamp ); + $this->status = self::unhandled; + } + + function setStatusAsHandled() { + + $this->status = self::handled; + //clear any error + $this->last_error_msg = ''; + } + + function setStatusAsBroken() { + + $this->status = self::broken; + } + + function getTimestamp() { + + return $this->timestamp; + } + + function set($name, $value) { + + $this->properties[$name] = $value; + } + + function get($name) { + + if(array_key_exists($name, $this->properties)) { + //print_r($this->properties[$name]); + return $this->properties[$name]; + } else { + return false; + } + } + + /** + * removes a property + */ + function delete( $name ) { + + if (array_key_exists( $name, $this->properties ) ) { + + unset( $this->properties[ $name ] ); + } + } + + /** + * Sets time related event properties + * + * @param integer $timestamp + */ + function setTime($timestamp = null) { + + if ( $timestamp ) { + $this->set('timestamp', $timestamp); + } else { + $timestamp = $this->getTimestamp(); + } + + $this->set('timestamp', $timestamp); + $this->set('year', date("Y", $timestamp)); + $this->set('month', date("Ym", $timestamp)); + $this->set('day', date("d", $timestamp)); + $this->set('yyyymmdd', date("Ymd", $timestamp)); + $this->set('dayofweek', date("D", $timestamp)); + $this->set('dayofyear', date("z", $timestamp)); + $this->set('weekofyear', date("W", $timestamp)); + $this->set('hour', date("G", $timestamp)); + $this->set('minute', date("i", $timestamp)); + $this->set('second', date("s", $timestamp)); + + //epoc time + list($msec, $sec) = explode(" ", microtime()); + $this->set('sec', $sec); + $this->set('msec', $msec); + + } + + function setCookieDomain($domain) { + + $this->properties['cookie_domain'] = $domain; + } + + /** + * Determines the time since the last request from this borwser + * + * @access private + * @return integer + */ + function timeSinceLastRequest() { + + return ($this->get('timestamp') - $this->get('last_req')); + } + + /** + * Applies calling application specific properties to request + * + * @access private + * @param array $properties + */ + function setProperties($properties = null) { + + if(!empty($properties)) { + + if (empty($this->properties)) { + $this->properties = $properties; + } else { + $this->properties = array_merge($this->properties, $properties); + } + } + } + + /** + * Adds new properties to the eventt without overwriting values + * for properties that are already set. + * + * @param array $properties + */ + function setNewProperties( $properties = array() ) { + + $this->properties = array_merge($properties, $this->properties); + + } + + /** + * Exports Event Class variables + * + * @return array + */ + function export() { + + return get_object_vars( $this ); + } + + /** + * Loads Event class variables from an array + * + * @param array $properties + */ + function loadFromArray ( $vars ) { + + $has = get_object_vars( $this ); + + foreach ($has as $name => $oldValue ) { + + if ( isset( $vars[$name] ) ) { + + $this->$name = $vars[ $name ]; + } + } + } + + function replaceProperties($properties) { + + $this->properties = $properties; + } + + /** + * Create guid from process id + * + * @return integer + * @access private + */ + function set_guid() { + + return owa_lib::generateRandomUid(); + } + + /** + * Create guid from string + * + * @param string $string + * @return integer + * @access private + */ + function set_string_guid($string) { + + return crc32(strtolower($string)); + + } + + /** + * Attempts to make a unique ID out of http request variables. + * This should only be used when storing state in a cookie is impossible. + * + * @return integer + */ + function setEnvGUID() { + + return crc32( $this->get('ua') . $this->get('ip_address') ); + + } + + function setSiteSessionState($site_id, $name, $value, $store_type = 'cookie') { + + $store_name = owa_coreAPI::getSetting('base', 'site_session_param').'_'.$site_id; + return owa_coreAPI::setState($store_name, $name, $value, $store_type, true); + } + + function deleteSiteSessionState($site_id, $store_type = 'cookie') { + + $store_name = owa_coreAPI::getSetting('base', 'site_session_param').'_'.$site_id; + return owa_coreAPI::clearState($store_name); + } + + function getProperties() { + + return $this->properties; + } + + function getEventType() { + + if (!empty($this->eventType)) { + return $this->eventType; + } elseif ($this->get('event_type')) { + return $this->get('event_type'); + } else { + + return 'unknown_event_type'; + } + } + + function setEventType($value) { + $this->eventType = $value; + } + + function cleanProperties() { + + return $this->setProperties(owa_lib::inputFilter($this->getProperties())); + } + + function setPageTitle($value) { + + $this->set('page_title', $value); + } + + function setSiteId($value) { + + $this->set('siteId', $value); + $this->set('site_id', $value); + } + + function getSiteId() { + + if ( $this->get('siteId') ) { + return $this->get('siteId'); + } else { + return $this->get('site_id'); + } + + + } + + function setPageType($value) { + + $this->set('page_type', $value); + } + + function getGuid() { + + return $this->guid; + } + + function getSiteSpecificGuid($site_id) { + + return owa_lib::generateRandomUid(); + } + + function getStatus() { + + return $this->status; + } + + function setDoNotReceiveBeforeTimestamp( $time ) { + + $this->do_not_receive_before_timestamp = $time; + } + + function wasReceived() { + + $time = time(); + + $this->last_receive_timestamp = $time; + + if ( $this->receive_count === 0 ) { + + $this->first_receive_timestamp = $time; + } + + $this->incrementReceiveCount(); + } + + function incrementReceiveCount() { + + $this->receive_count++; + } + + function getReceiveCount() { + + return $this->receive_count; + } + + function setErrorMeg( $error_msg ) { + + $this->last_error_msg = $error_msg; + } + + function getErrorMsg() { + + return $this->last_error_msg; + } + + function getLastReceiveTimestamp() { + + return $this->last_receive_timestamp; + } + + function getDoNotReceiveBeforeTimestamp() { + + return $this->do_not_receive_before_timestamp; + } + + // backwards compat for dbEventQueue. remove_soon. + function setOldQueueId( $id ) { + + if ( $id != $this->getGuid() ) { + + $this->old_queue_id = $id; + } + } + + function getQueueGuid() { + + if ( $this->old_queue_id ) { + + return $this->old_queue_id; + + } else { + + return $this->getGuid(); + } + } +} + ?> \ No newline at end of file diff --git a/modules/base/classes/eventDispatch.php b/modules/base/classes/eventDispatch.php index 8d59823c0..cb1221328 100644 --- a/modules/base/classes/eventDispatch.php +++ b/modules/base/classes/eventDispatch.php @@ -1,323 +1,323 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_eventDispatch { - - /** - * Stores listeners - * - */ - var $listeners = array(); - - /** - * Stores listener IDs by event type - * - */ - var $listenersByEventType = array(); - - /** - * Stores listener IDs by event type - * - */ - var $listenersByFilterType = array(); - - var $queues = array(); - - - /** - * Singleton - * - * @static - * @return object - * @access public - */ - public static function &get_instance() { - - static $ed; - - if ( ! $ed ) { - $ed = new owa_eventDispatch(); - } - - return $ed; - } - - /** - * Constructor - * - */ - function __construct() { - - } - - /** - * Attach - * - * Attaches observers by event type. - * Takes a valid user defined callback function for use by PHP's call_user_func_array - * - * @param $event_name string - * @param $observer mixed can be a function name or function array - * @return bool - */ - - function attach($event_name, $observer) { - - $id = owa_lib::generateRandomUid(); - // Register event names for this handler - if(is_array($event_name)) { - - foreach ($event_name as $k => $name) { - - $this->listenersByEventType[$name][] = $id; - } - - } else { - - $this->listenersByEventType[$event_name][] = $id; - } - - $this->listeners[$id] = $observer; - - return true; - } - - /** - * Attach - * - * Attaches observers by filter type. - * Takes a valid user defined callback function for use by PHP's call_user_func_array - * - * @param $filter_name string - * @param $observer mixed can be a function name or function array - * @return bool - */ - - function attachFilter($filter_name, $observer, $priority = 10) { - - $id = owa_lib::generateRandomUid(); - - $this->listenersByFilterType[$filter_name][$priority][] = $id; - - $this->listeners[$id] = $observer; - - } - - /** - * Notify - * - * Notifies all handlers of events in order that they were registered - * - * @param $event_type string - * @param $event array - * @return bool - */ - function notify($event) { - - $responses = array(); - owa_coreAPI::debug("Notifying listeners of ".$event->getEventType()); - //print_r($this->listenersByEventType[$event_type] ); - //print $event->getEventType(); - if (array_key_exists($event->getEventType(), $this->listenersByEventType)) { - $list = $this->listenersByEventType[$event->getEventType()]; - //print_r($list); - if (!empty($list)) { - foreach ($this->listenersByEventType[$event->getEventType()] as $k => $observer_id) { - //print_r($list); - $class = get_class( $this->listeners[$observer_id][0] ); - $responses[ $class ] = call_user_func_array($this->listeners[$observer_id], array($event)); - //owa_coreAPI::debug(print_r($event, true)); - owa_coreAPI::debug(sprintf("%s event handled by %s.",$event->getEventType(), get_class($this->listeners[$observer_id][0]))); - } - } - } else { - owa_coreAPI::debug("no listeners registered for this event type."); - } - - owa_coreAPI::debug('EHS: Responses - '.print_r($responses, true)); - - if ( in_array( OWA_EHS_EVENT_FAILED, $responses, true ) ) { - owa_coreAPI::debug("EHS: Event was not handled successfully by some handlers."); - $q = $this->getEventQueue( 'processing' ); - $q->sendMessage( $event ); - return OWA_EHS_EVENT_FAILED; - } else { - $event->setStatusAsHandled(); - owa_coreAPI::debug("EHS: Event was handled successfully by all handlers."); - return OWA_EHS_EVENT_HANDLED; - } - - } - - /** - * Notify Untill - * - * Notifies all handlers of events in order that they were registered - * Stops notifying after first handler returns true - * - * @param $event_type string - * @param $event array - * @return bool - */ - - function notifyUntill() { - owa_coreAPI::debug("Notifying Until listener for $event_type answers"); - } - - /** - * Filter - * - * Filters event by handlers in order that they were registered - * - * @param $filter_name string - * @param $value array - * @return $new_value mixed - */ - function filter($filter_name, $value = '') { - owa_coreAPI::debug("Filtering $filter_name"); - - if (array_key_exists($filter_name, $this->listenersByFilterType)) { - // sort the filter list by priority - ksort($this->listenersByFilterType[$filter_name]); - //get the function arguments - $args = func_get_args(); - // outer priority loop - foreach ($this->listenersByFilterType[$filter_name] as $priority) { - // inner filter class/function loop - foreach ($priority as $observer_id) { - // pass args to filter - - if (is_array($this->listeners[$observer_id])) { - - if ( is_object( $this->listeners[$observer_id][0] ) ) { - - $class = get_class( $this->listeners[$observer_id][0] ); - - } else { - // class could be passed as a string - $class = $this->listeners[$observer_id][0]; - } - - - $method = $this->listeners[$observer_id][1]; - $filter_method = $class . '::' . $method; - } else { - $filter_method = $this->listeners[$observer_id]; - } - - - - owa_coreAPI::debug(sprintf("Filter: %s. Value passed: %s", $filter_method, print_r($value, true))); - $value = call_user_func_array($this->listeners[$observer_id], array_slice($args,1)); - owa_coreAPI::debug(sprintf("Filter: %s. Value returned: %s", $filter_method, print_r($value, true))); - // set filterred value as value in args for next filter - $args[1] = $value; - // debug whats going on - owa_coreAPI::debug(sprintf("%s filtered by %s.", $filter_name, $filter_method)); - } - } - } - - return $value; - } - - /** - * Log - * - * Notifies handlers of tracking events - * Provides switch for async notification - * - * @param $event_params array - * @param $event_type string - * @depricated - */ - function log($event_params, $event_type = '') { - //owa_coreAPI::debug("Notifying listeners of tracking event type: $event_type"); - - if (!is_a($event_params,'owa_event')) { - $event = owa_coreAPI::supportClassFactory('base', 'event'); - $event->setProperties($event_params); - $event->setEventType($event_type); - } else { - $event = $event_params; - } - - $this->asyncNotify($event); - - } - - /** - * Async Notify - * - * Adds event to async notiication queue for notification by another process. - * - * @param $event array - * @return bool - * @depricated - */ - function asyncNotify( $event ) { - - return $this->notify( $event ); - } - - function getEventQueue( $name ) { - - return owa_coreAPI::getEventQueue( $name ); - } - - function eventFactory() { - - return owa_coreAPI::supportClassFactory('base', 'event'); - } - - function makeEvent($type = '') { - - $event = $this->eventFactory(); - - if ( $type ) { - $event->setEventType($type); - } - - return $event; - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_eventDispatch { + + /** + * Stores listeners + * + */ + var $listeners = array(); + + /** + * Stores listener IDs by event type + * + */ + var $listenersByEventType = array(); + + /** + * Stores listener IDs by event type + * + */ + var $listenersByFilterType = array(); + + var $queues = array(); + + + /** + * Singleton + * + * @static + * @return object + * @access public + */ + public static function &get_instance() { + + static $ed; + + if ( ! $ed ) { + $ed = new owa_eventDispatch(); + } + + return $ed; + } + + /** + * Constructor + * + */ + function __construct() { + + } + + /** + * Attach + * + * Attaches observers by event type. + * Takes a valid user defined callback function for use by PHP's call_user_func_array + * + * @param $event_name string + * @param $observer mixed can be a function name or function array + * @return bool + */ + + function attach($event_name, $observer) { + + $id = owa_lib::generateRandomUid(); + // Register event names for this handler + if(is_array($event_name)) { + + foreach ($event_name as $k => $name) { + + $this->listenersByEventType[$name][] = $id; + } + + } else { + + $this->listenersByEventType[$event_name][] = $id; + } + + $this->listeners[$id] = $observer; + + return true; + } + + /** + * Attach + * + * Attaches observers by filter type. + * Takes a valid user defined callback function for use by PHP's call_user_func_array + * + * @param $filter_name string + * @param $observer mixed can be a function name or function array + * @return bool + */ + + function attachFilter($filter_name, $observer, $priority = 10) { + + $id = owa_lib::generateRandomUid(); + + $this->listenersByFilterType[$filter_name][$priority][] = $id; + + $this->listeners[$id] = $observer; + + } + + /** + * Notify + * + * Notifies all handlers of events in order that they were registered + * + * @param $event_type string + * @param $event array + * @return bool + */ + function notify($event) { + + $responses = array(); + owa_coreAPI::debug("Notifying listeners of ".$event->getEventType()); + //print_r($this->listenersByEventType[$event_type] ); + //print $event->getEventType(); + if (array_key_exists($event->getEventType(), $this->listenersByEventType)) { + $list = $this->listenersByEventType[$event->getEventType()]; + //print_r($list); + if (!empty($list)) { + foreach ($this->listenersByEventType[$event->getEventType()] as $k => $observer_id) { + //print_r($list); + $class = get_class( $this->listeners[$observer_id][0] ); + $responses[ $class ] = call_user_func_array($this->listeners[$observer_id], array($event)); + //owa_coreAPI::debug(print_r($event, true)); + owa_coreAPI::debug(sprintf("%s event handled by %s.",$event->getEventType(), get_class($this->listeners[$observer_id][0]))); + } + } + } else { + owa_coreAPI::debug("no listeners registered for this event type."); + } + + owa_coreAPI::debug('EHS: Responses - '.print_r($responses, true)); + + if ( in_array( OWA_EHS_EVENT_FAILED, $responses, true ) ) { + owa_coreAPI::debug("EHS: Event was not handled successfully by some handlers."); + $q = $this->getEventQueue( 'processing' ); + $q->sendMessage( $event ); + return OWA_EHS_EVENT_FAILED; + } else { + $event->setStatusAsHandled(); + owa_coreAPI::debug("EHS: Event was handled successfully by all handlers."); + return OWA_EHS_EVENT_HANDLED; + } + + } + + /** + * Notify Untill + * + * Notifies all handlers of events in order that they were registered + * Stops notifying after first handler returns true + * + * @param $event_type string + * @param $event array + * @return bool + */ + + function notifyUntill() { + owa_coreAPI::debug("Notifying Until listener for $event_type answers"); + } + + /** + * Filter + * + * Filters event by handlers in order that they were registered + * + * @param $filter_name string + * @param $value array + * @return $new_value mixed + */ + function filter($filter_name, $value = '') { + owa_coreAPI::debug("Filtering $filter_name"); + + if (array_key_exists($filter_name, $this->listenersByFilterType)) { + // sort the filter list by priority + ksort($this->listenersByFilterType[$filter_name]); + //get the function arguments + $args = func_get_args(); + // outer priority loop + foreach ($this->listenersByFilterType[$filter_name] as $priority) { + // inner filter class/function loop + foreach ($priority as $observer_id) { + // pass args to filter + + if (is_array($this->listeners[$observer_id])) { + + if ( is_object( $this->listeners[$observer_id][0] ) ) { + + $class = get_class( $this->listeners[$observer_id][0] ); + + } else { + // class could be passed as a string + $class = $this->listeners[$observer_id][0]; + } + + + $method = $this->listeners[$observer_id][1]; + $filter_method = $class . '::' . $method; + } else { + $filter_method = $this->listeners[$observer_id]; + } + + + + owa_coreAPI::debug(sprintf("Filter: %s. Value passed: %s", $filter_method, print_r($value, true))); + $value = call_user_func_array($this->listeners[$observer_id], array_slice($args,1)); + owa_coreAPI::debug(sprintf("Filter: %s. Value returned: %s", $filter_method, print_r($value, true))); + // set filterred value as value in args for next filter + $args[1] = $value; + // debug whats going on + owa_coreAPI::debug(sprintf("%s filtered by %s.", $filter_name, $filter_method)); + } + } + } + + return $value; + } + + /** + * Log + * + * Notifies handlers of tracking events + * Provides switch for async notification + * + * @param $event_params array + * @param $event_type string + * @depricated + */ + function log($event_params, $event_type = '') { + //owa_coreAPI::debug("Notifying listeners of tracking event type: $event_type"); + + if (!is_a($event_params,'owa_event')) { + $event = owa_coreAPI::supportClassFactory('base', 'event'); + $event->setProperties($event_params); + $event->setEventType($event_type); + } else { + $event = $event_params; + } + + $this->asyncNotify($event); + + } + + /** + * Async Notify + * + * Adds event to async notiication queue for notification by another process. + * + * @param $event array + * @return bool + * @depricated + */ + function asyncNotify( $event ) { + + return $this->notify( $event ); + } + + function getEventQueue( $name ) { + + return owa_coreAPI::getEventQueue( $name ); + } + + function eventFactory() { + + return owa_coreAPI::supportClassFactory('base', 'event'); + } + + function makeEvent($type = '') { + + $event = $this->eventFactory(); + + if ( $type ) { + $event->setEventType($type); + } + + return $event; + } +} + ?> \ No newline at end of file diff --git a/modules/base/classes/eventQueue.php b/modules/base/classes/eventQueue.php index 3aeca11d3..37490854f 100644 --- a/modules/base/classes/eventQueue.php +++ b/modules/base/classes/eventQueue.php @@ -24,73 +24,73 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_eventQueue { - var $queue_name; - - function __construct( $map = array() ) { - - if ( ! isset( $map['queue_name'] ) ) { - $this->queue_name = 'somequeue'; - } else { - $this->queue_name = $map['queue_name']; - } - } - - // deprecated - function addToQueue( $event ) { - - return $this->sendMessage( $event ); - } - - function processQueue() { - - return false; - } - - function connect() { - - return true; - } - - function disconnect() { - - return true; - } - - function sendMessage( $event) { - - return false; - } - - function receiveMessage() { - - return false; - } - - function deleteMessage( $id ) { - - return true; - } - - function prepareMessage( $msg ) { - - return serialize( $msg ); - } - - function decodeMessage ( $msg ) { - - return unserialize( $msg ); - } - - function pruneArchive ( $interval ) { - - return false; - } + var $queue_name; + + function __construct( $map = array() ) { + + if ( ! isset( $map['queue_name'] ) ) { + $this->queue_name = 'somequeue'; + } else { + $this->queue_name = $map['queue_name']; + } + } + + // deprecated + function addToQueue( $event ) { + + return $this->sendMessage( $event ); + } + + function processQueue() { + + return false; + } + + function connect() { + + return true; + } + + function disconnect() { + + return true; + } + + function sendMessage( $event) { + + return false; + } + + function receiveMessage() { + + return false; + } + + function deleteMessage( $id ) { + + return true; + } + + function prepareMessage( $msg ) { + + return serialize( $msg ); + } + + function decodeMessage ( $msg ) { + + return unserialize( $msg ); + } + + function pruneArchive ( $interval ) { + + return false; + } } ?> \ No newline at end of file diff --git a/modules/base/classes/factTable.php b/modules/base/classes/factTable.php index 4eba24151..602feddb7 100644 --- a/modules/base/classes/factTable.php +++ b/modules/base/classes/factTable.php @@ -1,127 +1,127 @@ - - * @copyright Copyright © 2011 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.5.0 - */ - -class owa_factTable extends owa_entity { - - function __construct() { - - $columns = array(); - - $columns['id'] = new owa_dbColumn('id', OWA_DTD_BIGINT); - $columns['id']->setPrimaryKey(); - - $columns['visitor_id'] = new owa_dbColumn('visitor_id', OWA_DTD_BIGINT); - $columns['visitor_id']->setForeignKey('base.visitor'); - - $columns['session_id'] = new owa_dbColumn('session_id', OWA_DTD_BIGINT); - $columns['session_id']->setForeignKey('base.session'); - $columns['session_id']->setIndex(); - - $columns['site_id'] = new owa_dbColumn('site_id', OWA_DTD_VARCHAR255); - $columns['site_id']->setForeignKey('base.site', 'site_id'); - $columns['site_id']->setIndex(); - - $columns['referer_id'] = new owa_dbColumn('referer_id', OWA_DTD_BIGINT); - $columns['referer_id']->setForeignKey('base.referer'); - - $columns['ua_id'] = new owa_dbColumn('ua_id', OWA_DTD_BIGINT); - $columns['ua_id']->setForeignKey('base.ua'); - - $columns['host_id'] = new owa_dbColumn('host_id', OWA_DTD_BIGINT); - $columns['host_id']->setForeignKey('base.host'); - - $columns['os_id'] = new owa_dbColumn('os_id', OWA_DTD_BIGINT); - $columns['os_id']->setForeignKey('base.os'); - - $columns['location_id'] = new owa_dbColumn('location_id', OWA_DTD_BIGINT); - $columns['location_id']->setForeignKey('base.location_dim'); - - $columns['referring_search_term_id'] = new owa_dbColumn('referring_search_term_id', OWA_DTD_BIGINT); - $columns['referring_search_term_id']->setForeignKey('base.search_term_dim'); - - $columns['timestamp'] = new owa_dbColumn('timestamp', OWA_DTD_INT); - - $columns['yyyymmdd'] = new owa_dbColumn('yyyymmdd', OWA_DTD_INT); - $columns['yyyymmdd']->setIndex(); - - $columns['year'] = new owa_dbColumn('year', OWA_DTD_INT); - $columns['month'] = new owa_dbColumn('month', OWA_DTD_INT); - $columns['day'] = new owa_dbColumn('day', OWA_DTD_TINYINT2); - $columns['dayofweek'] = new owa_dbColumn('dayofweek', OWA_DTD_VARCHAR10); - $columns['dayofyear'] = new owa_dbColumn('dayofyear', OWA_DTD_INT); - $columns['weekofyear'] = new owa_dbColumn('weekofyear', OWA_DTD_INT); - - $columns['last_req'] = new owa_dbColumn( 'last_req', OWA_DTD_BIGINT ); - - $columns['ip_address'] = new owa_dbColumn('ip_address', OWA_DTD_VARCHAR255); - - $columns['is_new_visitor'] = new owa_dbColumn('is_new_visitor', OWA_DTD_BOOLEAN); - - $columns['is_repeat_visitor'] = new owa_dbColumn('is_repeat_visitor', OWA_DTD_BOOLEAN); - - $columns['language'] = new owa_dbColumn('language', OWA_DTD_VARCHAR255); - - $columns['days_since_prior_session'] = new owa_dbColumn( 'days_since_prior_session', OWA_DTD_INT ); - - $columns['days_since_first_session'] = new owa_dbColumn( 'days_since_first_session', OWA_DTD_INT ); - - $columns['num_prior_sessions'] = new owa_dbColumn( 'num_prior_sessions', OWA_DTD_INT ); - - $columns['medium'] = new owa_dbColumn( 'medium', OWA_DTD_VARCHAR255 ); - - $columns['source_id'] = new owa_dbColumn( 'source_id', OWA_DTD_BIGINT ); - $columns['source_id']->setForeignKey('base.source_dim'); - - $columns['ad_id'] = new owa_dbColumn( 'ad_id', OWA_DTD_BIGINT ); - $columns['ad_id']->setForeignKey('base.ad_dim'); - - $columns['campaign_id'] = new owa_dbColumn( 'campaign_id', OWA_DTD_BIGINT ); - $columns['campaign_id']->setForeignKey( 'base.campaign_dim' ); - - $columns['user_name'] = new owa_dbColumn( 'user_name', OWA_DTD_VARCHAR255 ); - - // custom variable columns - $cv_max = owa_coreAPI::getSetting( 'base', 'maxCustomVars' ); - for ($i = 1; $i <= $cv_max;$i++) { - - $cvar_name_col = 'cv'.$i.'_name'; - $columns[$cvar_name_col] = new owa_dbColumn( $cvar_name_col, OWA_DTD_VARCHAR255 ); - - $cvar_value_col = 'cv'.$i.'_value'; - $columns[$cvar_value_col] = new owa_dbColumn( $cvar_value_col, OWA_DTD_VARCHAR255 ); - } - - return $columns; - } - } - + + * @copyright Copyright © 2011 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.5.0 + */ + +class owa_factTable extends owa_entity { + + function __construct() { + + $columns = array(); + + $columns['id'] = new owa_dbColumn('id', OWA_DTD_BIGINT); + $columns['id']->setPrimaryKey(); + + $columns['visitor_id'] = new owa_dbColumn('visitor_id', OWA_DTD_BIGINT); + $columns['visitor_id']->setForeignKey('base.visitor'); + + $columns['session_id'] = new owa_dbColumn('session_id', OWA_DTD_BIGINT); + $columns['session_id']->setForeignKey('base.session'); + $columns['session_id']->setIndex(); + + $columns['site_id'] = new owa_dbColumn('site_id', OWA_DTD_VARCHAR255); + $columns['site_id']->setForeignKey('base.site', 'site_id'); + $columns['site_id']->setIndex(); + + $columns['referer_id'] = new owa_dbColumn('referer_id', OWA_DTD_BIGINT); + $columns['referer_id']->setForeignKey('base.referer'); + + $columns['ua_id'] = new owa_dbColumn('ua_id', OWA_DTD_BIGINT); + $columns['ua_id']->setForeignKey('base.ua'); + + $columns['host_id'] = new owa_dbColumn('host_id', OWA_DTD_BIGINT); + $columns['host_id']->setForeignKey('base.host'); + + $columns['os_id'] = new owa_dbColumn('os_id', OWA_DTD_BIGINT); + $columns['os_id']->setForeignKey('base.os'); + + $columns['location_id'] = new owa_dbColumn('location_id', OWA_DTD_BIGINT); + $columns['location_id']->setForeignKey('base.location_dim'); + + $columns['referring_search_term_id'] = new owa_dbColumn('referring_search_term_id', OWA_DTD_BIGINT); + $columns['referring_search_term_id']->setForeignKey('base.search_term_dim'); + + $columns['timestamp'] = new owa_dbColumn('timestamp', OWA_DTD_INT); + + $columns['yyyymmdd'] = new owa_dbColumn('yyyymmdd', OWA_DTD_INT); + $columns['yyyymmdd']->setIndex(); + + $columns['year'] = new owa_dbColumn('year', OWA_DTD_INT); + $columns['month'] = new owa_dbColumn('month', OWA_DTD_INT); + $columns['day'] = new owa_dbColumn('day', OWA_DTD_TINYINT2); + $columns['dayofweek'] = new owa_dbColumn('dayofweek', OWA_DTD_VARCHAR10); + $columns['dayofyear'] = new owa_dbColumn('dayofyear', OWA_DTD_INT); + $columns['weekofyear'] = new owa_dbColumn('weekofyear', OWA_DTD_INT); + + $columns['last_req'] = new owa_dbColumn( 'last_req', OWA_DTD_BIGINT ); + + $columns['ip_address'] = new owa_dbColumn('ip_address', OWA_DTD_VARCHAR255); + + $columns['is_new_visitor'] = new owa_dbColumn('is_new_visitor', OWA_DTD_BOOLEAN); + + $columns['is_repeat_visitor'] = new owa_dbColumn('is_repeat_visitor', OWA_DTD_BOOLEAN); + + $columns['language'] = new owa_dbColumn('language', OWA_DTD_VARCHAR255); + + $columns['days_since_prior_session'] = new owa_dbColumn( 'days_since_prior_session', OWA_DTD_INT ); + + $columns['days_since_first_session'] = new owa_dbColumn( 'days_since_first_session', OWA_DTD_INT ); + + $columns['num_prior_sessions'] = new owa_dbColumn( 'num_prior_sessions', OWA_DTD_INT ); + + $columns['medium'] = new owa_dbColumn( 'medium', OWA_DTD_VARCHAR255 ); + + $columns['source_id'] = new owa_dbColumn( 'source_id', OWA_DTD_BIGINT ); + $columns['source_id']->setForeignKey('base.source_dim'); + + $columns['ad_id'] = new owa_dbColumn( 'ad_id', OWA_DTD_BIGINT ); + $columns['ad_id']->setForeignKey('base.ad_dim'); + + $columns['campaign_id'] = new owa_dbColumn( 'campaign_id', OWA_DTD_BIGINT ); + $columns['campaign_id']->setForeignKey( 'base.campaign_dim' ); + + $columns['user_name'] = new owa_dbColumn( 'user_name', OWA_DTD_VARCHAR255 ); + + // custom variable columns + $cv_max = owa_coreAPI::getSetting( 'base', 'maxCustomVars' ); + for ($i = 1; $i <= $cv_max;$i++) { + + $cvar_name_col = 'cv'.$i.'_name'; + $columns[$cvar_name_col] = new owa_dbColumn( $cvar_name_col, OWA_DTD_VARCHAR255 ); + + $cvar_value_col = 'cv'.$i.'_value'; + $columns[$cvar_value_col] = new owa_dbColumn( $cvar_value_col, OWA_DTD_VARCHAR255 ); + } + + return $columns; + } + } + ?> \ No newline at end of file diff --git a/modules/base/classes/fileCache.php b/modules/base/classes/fileCache.php index a4ba30489..a032e7a96 100644 --- a/modules/base/classes/fileCache.php +++ b/modules/base/classes/fileCache.php @@ -26,271 +26,271 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_fileCache extends owa_cache { - var $cache_dir; - var $lock_file_name = 'cache.lock'; - var $cache_file_header = ''; - var $file_perms = 0750; - var $dir_perms = 0750; - var $mutex; - - /** - * Constructor - * - * Takes cache directory as param - * - * @param $cache_dir string - */ - function __construct($cache_dir = '') { - - if ($cache_dir) { - $this->cache_dir = $cache_dir; - } else { - $this->cache_dir = OWA_CACHE_DIR; - } - - return parent::__construct(); - } - - function getItemFromCacheStore($collection, $id) { - - $cache_file = $this->makeCollectionDirPath($collection).$id.'.php'; - $this->debug("check cache file: ".$cache_file); - - // if no cache file then return false - if (!file_exists($cache_file)) { - $this->debug(sprintf('Cache File not found for Collection: %s, id: %s, file: %s', $collection, $id, $cache_file)); - return false; - - // cache object has expired - } elseif ((filectime($cache_file) + $this->getCollectionExpirationPeriod($collection)) < time()) { - $this->debug("time: ".time()); - $this->debug("ctime: ".filectime($cache_file)); - $this->debug("diff: ".(time() - filectime($cache_file))); - $this->debug("exp period: ".$this->getCollectionExpirationPeriod($collection)); - $this->removeCacheFile($this->makeCollectionDirPath($collection).$id.'.php'); - $this->debug(sprintf('Cache Object has expired for Collection: %s, id: %s', $collection, $id)); - return false; - - // load from cache file - } else { - return unserialize(base64_decode(substr(@ file_get_contents($cache_file), strlen($this->cache_file_header), -strlen($this->cache_file_footer)))); - } - - } - - function putItemToCacheStore($collection, $id) { - - if ( $this->acquire_lock() ) { - $this->makeCacheCollectionDir($collection); - $this->debug(' writing file for: '.$collection.$id); - // create collection dir - $collection_dir = $this->makeCollectionDirPath($collection); - // asemble cache file name - $cache_file = $collection_dir.$id.'.php'; - - $this->removeCacheFile($cache_file); - - $temp_cache_file = tempnam($collection_dir, 'tmp_'.$id); - - $data = $this->cache_file_header.base64_encode(serialize($this->cache[$collection][$id])).$this->cache_file_footer; - - - // open the temp cache file for writing - $tcf_handle = @fopen($temp_cache_file, 'w'); - - if ( false === $tcf_handle ) { - $this->debug('could not acquire temp file handler'); - } else { - - fputs($tcf_handle, $data); - - fclose($tcf_handle); - - if (!@ rename($temp_cache_file, $cache_file)) { - - if (!@ copy($temp_cache_file, $cache_file)) { - $this->debug('could not rename or copy temp file to cache file'); - } else { - @ unlink($temp_cache_file); - $this->debug('removing temp cache file'); - } - } - - @ chmod($cache_file, $this->file_perms); - $this->debug('changing file permissions on cache file'); - } - - $this->release_lock(); - } else { - $this->debug("could not persist item to cache due to failure acquiring lock."); - } - } - - function removeItemFromCacheStore($collection, $id) { - - return $this->removeCacheFile($this->makeCollectionDirPath($collection).$id.'.php'); - } - - function makeCollectionDirPath($collection) { - - if (!in_array($collection, $this->global_collections)) { - return $this->cache_dir.$this->cache_id.'/'.$collection.'/'; - } else { - return $this->cache_dir.$collection.'/'; - } - } - - function makeCacheCollectionDir($collection) { - - // check to see if the caches directory is writable, return if not. - if (!is_writable($this->cache_dir)) { - return; - } - - // localize the cache directory based on some id passed from caller - - if (!file_exists($this->cache_dir.$this->cache_id)) { - - mkdir($this->cache_dir.$this->cache_id); - chmod($this->cache_dir.$this->cache_id, $this->dir_perms); - } - - $collection_dir = $this->makeCollectionDirPath($collection); - - if (!file_exists($collection_dir)) { - - mkdir($collection_dir); - chmod($collection_dir, $this->dir_perms); - } - - if (!file_exists($collection_dir."index.php")) { - - touch($collection_dir."index.php"); - chmod($collection_dir."index.php", $this->file_perms); - } - } - - function removeCacheFile($cache_file) { - - // Remove the cache file - if (file_exists($cache_file)) { - @ unlink($cache_file); - $this->debug('Cache File Removed: '.$cache_file); - $this->statistics['removed']++; - return true; - } else { - $this->debug('Cache File does not exist: '.$cache_file); - return false; - } - } - - function flush() { - - $tld = $this->readDir($this->cache_dir); - - - if ( array_key_exists( 'files', $tld ) ) { - - //$this->deleteFiles($tld['files']); - } - - foreach ($tld['dirs'] as $k => $dir) { - - $sld = $this->readDir($dir); - - if ( array_key_exists( 'files', $sld ) ) { - - $this->deleteFiles( $sld['files'] ); - } - - foreach ( $sld['dirs'] as $sk => $sdir ) { - - $ssld = $this->readDir( $sdir ); - - if ( array_key_exists( 'files', $ssld ) ) { - - $this->deleteFiles( $ssld['files'] ); - } - } - } - } - - function setCacheDir($dir) { - - $this->cache_dir = $dir; - } - - function acquire_lock() { - // Acquire a write lock. - $this->mutex = @fopen($this->cache_dir.$this->lock_file_name, 'w'); - if (false == $this->mutex) { - return false; - } else { - flock($this->mutex, LOCK_EX); - return true; - } - } - - function release_lock() { + var $cache_dir; + var $lock_file_name = 'cache.lock'; + var $cache_file_header = ''; + var $file_perms = 0750; + var $dir_perms = 0750; + var $mutex; + + /** + * Constructor + * + * Takes cache directory as param + * + * @param $cache_dir string + */ + function __construct($cache_dir = '') { + + if ($cache_dir) { + $this->cache_dir = $cache_dir; + } else { + $this->cache_dir = OWA_CACHE_DIR; + } + + return parent::__construct(); + } + + function getItemFromCacheStore($collection, $id) { + + $cache_file = $this->makeCollectionDirPath($collection).$id.'.php'; + $this->debug("check cache file: ".$cache_file); + + // if no cache file then return false + if (!file_exists($cache_file)) { + $this->debug(sprintf('Cache File not found for Collection: %s, id: %s, file: %s', $collection, $id, $cache_file)); + return false; + + // cache object has expired + } elseif ((filectime($cache_file) + $this->getCollectionExpirationPeriod($collection)) < time()) { + $this->debug("time: ".time()); + $this->debug("ctime: ".filectime($cache_file)); + $this->debug("diff: ".(time() - filectime($cache_file))); + $this->debug("exp period: ".$this->getCollectionExpirationPeriod($collection)); + $this->removeCacheFile($this->makeCollectionDirPath($collection).$id.'.php'); + $this->debug(sprintf('Cache Object has expired for Collection: %s, id: %s', $collection, $id)); + return false; + + // load from cache file + } else { + return unserialize(base64_decode(substr(@ file_get_contents($cache_file), strlen($this->cache_file_header), -strlen($this->cache_file_footer)))); + } + + } + + function putItemToCacheStore($collection, $id) { + + if ( $this->acquire_lock() ) { + $this->makeCacheCollectionDir($collection); + $this->debug(' writing file for: '.$collection.$id); + // create collection dir + $collection_dir = $this->makeCollectionDirPath($collection); + // asemble cache file name + $cache_file = $collection_dir.$id.'.php'; + + $this->removeCacheFile($cache_file); + + $temp_cache_file = tempnam($collection_dir, 'tmp_'.$id); + + $data = $this->cache_file_header.base64_encode(serialize($this->cache[$collection][$id])).$this->cache_file_footer; + + + // open the temp cache file for writing + $tcf_handle = @fopen($temp_cache_file, 'w'); + + if ( false === $tcf_handle ) { + $this->debug('could not acquire temp file handler'); + } else { + + fputs($tcf_handle, $data); + + fclose($tcf_handle); + + if (!@ rename($temp_cache_file, $cache_file)) { + + if (!@ copy($temp_cache_file, $cache_file)) { + $this->debug('could not rename or copy temp file to cache file'); + } else { + @ unlink($temp_cache_file); + $this->debug('removing temp cache file'); + } + } + + @ chmod($cache_file, $this->file_perms); + $this->debug('changing file permissions on cache file'); + } + + $this->release_lock(); + } else { + $this->debug("could not persist item to cache due to failure acquiring lock."); + } + } + + function removeItemFromCacheStore($collection, $id) { + + return $this->removeCacheFile($this->makeCollectionDirPath($collection).$id.'.php'); + } + + function makeCollectionDirPath($collection) { + + if (!in_array($collection, $this->global_collections)) { + return $this->cache_dir.$this->cache_id.'/'.$collection.'/'; + } else { + return $this->cache_dir.$collection.'/'; + } + } + + function makeCacheCollectionDir($collection) { + + // check to see if the caches directory is writable, return if not. + if (!is_writable($this->cache_dir)) { + return; + } + + // localize the cache directory based on some id passed from caller + + if (!file_exists($this->cache_dir.$this->cache_id)) { + + mkdir($this->cache_dir.$this->cache_id); + chmod($this->cache_dir.$this->cache_id, $this->dir_perms); + } + + $collection_dir = $this->makeCollectionDirPath($collection); + + if (!file_exists($collection_dir)) { + + mkdir($collection_dir); + chmod($collection_dir, $this->dir_perms); + } + + if (!file_exists($collection_dir."index.php")) { + + touch($collection_dir."index.php"); + chmod($collection_dir."index.php", $this->file_perms); + } + } + + function removeCacheFile($cache_file) { + + // Remove the cache file + if (file_exists($cache_file)) { + @ unlink($cache_file); + $this->debug('Cache File Removed: '.$cache_file); + $this->statistics['removed']++; + return true; + } else { + $this->debug('Cache File does not exist: '.$cache_file); + return false; + } + } + + function flush() { + + $tld = $this->readDir($this->cache_dir); + + + if ( array_key_exists( 'files', $tld ) ) { + + //$this->deleteFiles($tld['files']); + } + + foreach ($tld['dirs'] as $k => $dir) { + + $sld = $this->readDir($dir); + + if ( array_key_exists( 'files', $sld ) ) { + + $this->deleteFiles( $sld['files'] ); + } + + foreach ( $sld['dirs'] as $sk => $sdir ) { + + $ssld = $this->readDir( $sdir ); + + if ( array_key_exists( 'files', $ssld ) ) { + + $this->deleteFiles( $ssld['files'] ); + } + } + } + } + + function setCacheDir($dir) { + + $this->cache_dir = $dir; + } + + function acquire_lock() { + // Acquire a write lock. + $this->mutex = @fopen($this->cache_dir.$this->lock_file_name, 'w'); + if (false == $this->mutex) { + return false; + } else { + flock($this->mutex, LOCK_EX); + return true; + } + } + + function release_lock() { // Release write lock. flock($this->mutex, LOCK_UN); - fclose($this->mutex); - } - - function readDir($dir) { - - $this->debug( "Reading cache file list from: ". $dir ); - - $data = array(); - - if ($handle = opendir($dir)) { - - while (($file = readdir($handle)) !== false) { - - if (is_dir($dir.$file)) { - - if (strpos($file, '.') === false) { - $data['dirs'][] = $dir.$file.'/'; - } - } else { - if (strpos($file, '.php') == true) { - $data['files'][] = $dir.$file; - } - - if (strpos($file, '.lock') == true) { - $data['files'][] = $dir.$file; - } - } - } - - } - - closedir($handle); - return $data; - } - - function deleteFiles($files) { - - if (!empty($files)) { - - foreach ($files as $file) { - $this->debug("About to unlink cache file: ".$file); - unlink($file); - } - - } else { - owa_coreAPI::debug('No Cache Files to delete.'); - } - - return true; - } + fclose($this->mutex); + } + + function readDir($dir) { + + $this->debug( "Reading cache file list from: ". $dir ); + + $data = array(); + + if ($handle = opendir($dir)) { + + while (($file = readdir($handle)) !== false) { + + if (is_dir($dir.$file)) { + + if (strpos($file, '.') === false) { + $data['dirs'][] = $dir.$file.'/'; + } + } else { + if (strpos($file, '.php') == true) { + $data['files'][] = $dir.$file; + } + + if (strpos($file, '.lock') == true) { + $data['files'][] = $dir.$file; + } + } + } + + } + + closedir($handle); + return $data; + } + + function deleteFiles($files) { + + if (!empty($files)) { + + foreach ($files as $file) { + $this->debug("About to unlink cache file: ".$file); + unlink($file); + } + + } else { + owa_coreAPI::debug('No Cache Files to delete.'); + } + + return true; + } } diff --git a/modules/base/classes/fileEventQueue.php b/modules/base/classes/fileEventQueue.php index 17f2b6e64..f08944a65 100644 --- a/modules/base/classes/fileEventQueue.php +++ b/modules/base/classes/fileEventQueue.php @@ -17,10 +17,10 @@ // if ( ! class_exists( 'owa_eventQueue' ) ) { - require_once( OWA_BASE_CLASS_DIR.'eventQueue.php' ); + require_once( OWA_BASE_CLASS_DIR.'eventQueue.php' ); } if ( ! class_exists( 'owa_event' ) ) { - require_once(OWA_BASE_CLASS_DIR.'event.php'); + require_once(OWA_BASE_CLASS_DIR.'event.php'); } require_once(OWA_PEARLOG_DIR . '/Log.php'); require_once(OWA_PEARLOG_DIR . '/Log/file.php'); @@ -33,319 +33,319 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_fileEventQueue extends owa_eventQueue { - - var $queue; - var $queue_dir; - var $event_file; - var $date_format; - var $unprocessed_path; - var $archive_path; - var $rotation_size; - var $rotation_interval = 3600; - var $currentProcessingFileHandle; - - function __construct( $map = array() ) { - - parent::__construct( $map ); - - // set event file - if ( ! isset( $map['path'] ) ) { - $this->queue_dir = owa_coreAPI::getSetting('base', 'async_log_dir'); - } else { - $this->queue_dir = $map['path']; - - } - - // set directory where unprocessed, rotated files reside - if ( ! isset( $map['unprocessed_path'] ) ) { - - $this->unprocessed_path = $this->queue_dir . 'unprocessed/'; - - } else { - $this->unprocessed_path = $map['unprocessed_path']; - } - - // test or make dir - if ( ! is_dir( $this->unprocessed_path ) && ! mkdir( $this->unprocessed_path, 0755 ) ) { - - throw new Exception("Cannot make unprocessed directory."); - } - - // set directory where processed files will be archived. - if ( ! isset( $map['archive_path'] ) ) { - $this->archive_path = $this->queue_dir . 'archive/'; - } else { - $this->archive_path = $map['archive_path']; - } - - // test or make dir - if ( ! is_dir( $this->archive_path ) && ! mkdir( $this->archive_path, 0755 ) ) { - - throw new Exception("Cannot make archive directory."); - } - - if ( ! isset( $map['date_format'] ) ) { - $this->date_format = "Y-m-d-H-is"; - } - - if ( ! isset( $map['rotation_interval'] ) ) { - $this->rotation_interval = $map['rotation_interval']; - } - - $this->event_file = $this->queue_dir. 'events.txt'; - $this->lock_file = $this->queue_dir.'lock.txt'; - - return parent::__construct( $map ); - } - - function makeQueue() { - - //make file queue - $conf = array('mode' => 0600, 'timeFormat' => '%X %x'); - //$this->queue = &Log::singleton('async_queue', $this->event_file, 'async_event_queue', $conf); - $this->queue = Log::singleton('file', $this->event_file, $this->queue_name, $conf); - $this->queue->_lineFormat = '%1$s|*|%2$s|*|[%3$s]|*|%4$s'; - // not sure why this is needed but it is. - $this->queue->_filename = $this->event_file; - } - - function openFile( $file ) { - - // check to see if event log file exisits - if ( file_exists( $file ) && is_readable( $file ) ) { - //create lock file - $this->create_lock_file(); - return @fopen($file, "r"); - } else { - throw new Exception("Cannot open queue file at ".$file); - } - } - - function closeFile( $handle ) { - - fclose( $handle ); - } - - function isLocked() { - - if ( file_exists( $this->lock_file ) ) { - //read contents of lock file for last PID - $lock = fopen( $this->lock_file, "r" ) or die ("Could not read lock file"); - if ($lock) { - while (!feof($lock)) { - $former_pid = fgets($lock, 4096); - } - fclose($lock); - } - - //check to see if former process is still running - $ps_check = $this->isRunning($former_pid); - //if the process is still running, exit. - if ($ps_check) { - owa_coreAPI::notice(sprintf('Previous Process (%d) still active. Terminating Run.', $former_pid)); - return true; - //if it's not running remove the lock file and proceead. - } else { - owa_coreAPI::debug(sprintf('Process %d is no longer running. Deleting old Lock file. \n', $former_pid)); - unlink ($this->lock_file); - return false; - } - - } else { - return false; - } - } - - function isRunning($pid) { - - $process_state = ''; + + var $queue; + var $queue_dir; + var $event_file; + var $date_format; + var $unprocessed_path; + var $archive_path; + var $rotation_size; + var $rotation_interval = 3600; + var $currentProcessingFileHandle; + + function __construct( $map = array() ) { + + parent::__construct( $map ); + + // set event file + if ( ! isset( $map['path'] ) ) { + $this->queue_dir = owa_coreAPI::getSetting('base', 'async_log_dir'); + } else { + $this->queue_dir = $map['path']; + + } + + // set directory where unprocessed, rotated files reside + if ( ! isset( $map['unprocessed_path'] ) ) { + + $this->unprocessed_path = $this->queue_dir . 'unprocessed/'; + + } else { + $this->unprocessed_path = $map['unprocessed_path']; + } + + // test or make dir + if ( ! is_dir( $this->unprocessed_path ) && ! mkdir( $this->unprocessed_path, 0755 ) ) { + + throw new Exception("Cannot make unprocessed directory."); + } + + // set directory where processed files will be archived. + if ( ! isset( $map['archive_path'] ) ) { + $this->archive_path = $this->queue_dir . 'archive/'; + } else { + $this->archive_path = $map['archive_path']; + } + + // test or make dir + if ( ! is_dir( $this->archive_path ) && ! mkdir( $this->archive_path, 0755 ) ) { + + throw new Exception("Cannot make archive directory."); + } + + if ( ! isset( $map['date_format'] ) ) { + $this->date_format = "Y-m-d-H-is"; + } + + if ( ! isset( $map['rotation_interval'] ) ) { + $this->rotation_interval = $map['rotation_interval']; + } + + $this->event_file = $this->queue_dir. 'events.txt'; + $this->lock_file = $this->queue_dir.'lock.txt'; + + return parent::__construct( $map ); + } + + function makeQueue() { + + //make file queue + $conf = array('mode' => 0600, 'timeFormat' => '%X %x'); + //$this->queue = &Log::singleton('async_queue', $this->event_file, 'async_event_queue', $conf); + $this->queue = Log::singleton('file', $this->event_file, $this->queue_name, $conf); + $this->queue->_lineFormat = '%1$s|*|%2$s|*|[%3$s]|*|%4$s'; + // not sure why this is needed but it is. + $this->queue->_filename = $this->event_file; + } + + function openFile( $file ) { + + // check to see if event log file exisits + if ( file_exists( $file ) && is_readable( $file ) ) { + //create lock file + $this->create_lock_file(); + return @fopen($file, "r"); + } else { + throw new Exception("Cannot open queue file at ".$file); + } + } + + function closeFile( $handle ) { + + fclose( $handle ); + } + + function isLocked() { + + if ( file_exists( $this->lock_file ) ) { + //read contents of lock file for last PID + $lock = fopen( $this->lock_file, "r" ) or die ("Could not read lock file"); + if ($lock) { + while (!feof($lock)) { + $former_pid = fgets($lock, 4096); + } + fclose($lock); + } + + //check to see if former process is still running + $ps_check = $this->isRunning($former_pid); + //if the process is still running, exit. + if ($ps_check) { + owa_coreAPI::notice(sprintf('Previous Process (%d) still active. Terminating Run.', $former_pid)); + return true; + //if it's not running remove the lock file and proceead. + } else { + owa_coreAPI::debug(sprintf('Process %d is no longer running. Deleting old Lock file. \n', $former_pid)); + unlink ($this->lock_file); + return false; + } + + } else { + return false; + } + } + + function isRunning($pid) { + + $process_state = ''; - exec("ps $pid", $process_state); - //print $pid; - //print_r($process_state); + exec("ps $pid", $process_state); + //print $pid; + //print_r($process_state); - if (count($process_state) >= 2) { - return true; - } else { - return false; - } - } - - function sendMessage($event) { - - if ( ! $this->queue ) { - $this->makeQueue(); - } - - $this->queue->log( urlencode( serialize( $event ) ) ); - } - - - function receiveMessage() { - owa_coreAPI::notice("receive event."); - $qfile = $this->getNextUnprocessedQueueFile(); - - if ( ! $this->currentProcessingFileHandle ) { - - if ( $qfile ) { - // set current processing file handle to - owa_coreAPI::notice("Opening queue file $qfile to process."); - - $this->currentProcessingFileHandle = $this->openFile( $qfile ); - } else { - - owa_coreAPI::notice('No queue file to process.'); - return false; - } - } - - if ( $this->currentProcessingFileHandle ) { - - $buffer = fgets( $this->currentProcessingFileHandle ); - - if ( ! feof( $this->currentProcessingFileHandle ) ) { - - // Parse the row - //owa_coreAPI::debug('returning buffer: '. print_r( $buffer, true)); - //owa_coreAPI::debug('returning buffer: '. print_r( $buffer, true)); - $event = $this->parse_log_row( $buffer ); - //owa_coreAPI::debug('returning event: '. print_r( $event, true)); - $event->wasReceived(); - return $event; - - } else { - // if it is the end of file then, close, archive and move onto the next file. - owa_coreAPI::notice('EOF reached.'); - $this->closeFile( $this->currentProcessingFileHandle ); - $this->currentProcessingFileHandle = ''; - - if ( owa_coreAPI::getSetting( 'base', 'archive_old_events' ) ) { - - $this->archiveProcessedFile( $qfile ); - - } else { - - $this->deleteFile( $qfile ); - } - - owa_coreAPI::notice('Moving on to next queue file.'); - - return $this->receiveMessage(); - - } - - } else { - owa_coreAPI::notice('still no queue to process.'); - return false; - } - } - - function getNextUnprocessedQueueFile() { - - // get a list of all unprocesed queue files - $qfiles = $this->getUnprocessedFileList(); - owa_coreAPI::notice('queue files to process: '.print_r($qfiles, true)); - // get earliest queue file based on creation time so we can process them in order - if ( $qfiles && is_array( $qfiles ) ) { - - return array_shift( $qfiles ); - - } else { - - return owa_coreAPI::notice('No unprocessed queue files to process.'); - } - } - - function getUnprocessedFileList() { - - $files = array(); - - $this->rotateEventFile(); - - if ( is_dir( $this->unprocessed_path ) ) { - foreach ( new DirectoryIterator( $this->unprocessed_path ) as $item ) { - if ( $item->isFile() && ! $item->isDot() ) { - $files[ $item->getMTime() ] = $item->getPathname(); - } - } - - // sort by key ascending - ksort( $files ); - } - - return $files; - } - - function pruneArchive( $interval ) { - - if ( is_dir( $this->archive_path ) ) { - - foreach ( new DirectoryIterator( $this->archive_path ) as $item ) { - - if ( $item->isFile() && - ! $item->isDot() && - $item->getMTime() < ( time() - $interval ) ) - { - owa_coreAPI::notice('about to unlink' . $item->getRealPath()); - $this->deleteFile( $item->getRealPath() ); - } - } - } - } - - function deleteFile( $path ) { - - return unlink( $path ); - } - - function rotateEventFile() { - - if ( file_exists( $this->event_file ) ) { - - // Create a new log file name - $new_file_path = sprintf("%s-eventfile-%s.txt", $this->unprocessed_path . $this->queue_name, date( $this->date_format ) ); - $ret = owa_lib::moveFile( $this->event_file, $new_file_path ); - - if ( $ret ) { - owa_coreAPI::debug('Rotated event file.'); - } else { - owa_coreAPI::debug('Could not rotate event file.'); - } - } - } - - function archiveProcessedFile( $file ) { - - $new_file_path = $this->archive_path . basename( $file ); - $ret = owa_lib::moveFile( $file, $new_file_path ); - } - - - function parse_log_row( $row ) { - - if ($row) { - $raw_event = explode("|*|", $row); - $row_array = array( 'timestamp' => $raw_event[0], 'event_obj' => $raw_event[3]); - $event = unserialize(urldecode($row_array['event_obj'])); - return $event; - } - } - - function create_lock_file() { - - $lock_file = fopen($this->lock_file, "w+") or die ("Could not create lock file at: ".$this->lock_file); - - // Write PID to lock file - if (fwrite($lock_file, getmypid()) === FALSE) { - owa_coreAPI::debug('Cannot write to lock file. Terminating Run.'); - exit; - } - } + if (count($process_state) >= 2) { + return true; + } else { + return false; + } + } + + function sendMessage($event) { + + if ( ! $this->queue ) { + $this->makeQueue(); + } + + $this->queue->log( urlencode( serialize( $event ) ) ); + } + + + function receiveMessage() { + owa_coreAPI::notice("receive event."); + $qfile = $this->getNextUnprocessedQueueFile(); + + if ( ! $this->currentProcessingFileHandle ) { + + if ( $qfile ) { + // set current processing file handle to + owa_coreAPI::notice("Opening queue file $qfile to process."); + + $this->currentProcessingFileHandle = $this->openFile( $qfile ); + } else { + + owa_coreAPI::notice('No queue file to process.'); + return false; + } + } + + if ( $this->currentProcessingFileHandle ) { + + $buffer = fgets( $this->currentProcessingFileHandle ); + + if ( ! feof( $this->currentProcessingFileHandle ) ) { + + // Parse the row + //owa_coreAPI::debug('returning buffer: '. print_r( $buffer, true)); + //owa_coreAPI::debug('returning buffer: '. print_r( $buffer, true)); + $event = $this->parse_log_row( $buffer ); + //owa_coreAPI::debug('returning event: '. print_r( $event, true)); + $event->wasReceived(); + return $event; + + } else { + // if it is the end of file then, close, archive and move onto the next file. + owa_coreAPI::notice('EOF reached.'); + $this->closeFile( $this->currentProcessingFileHandle ); + $this->currentProcessingFileHandle = ''; + + if ( owa_coreAPI::getSetting( 'base', 'archive_old_events' ) ) { + + $this->archiveProcessedFile( $qfile ); + + } else { + + $this->deleteFile( $qfile ); + } + + owa_coreAPI::notice('Moving on to next queue file.'); + + return $this->receiveMessage(); + + } + + } else { + owa_coreAPI::notice('still no queue to process.'); + return false; + } + } + + function getNextUnprocessedQueueFile() { + + // get a list of all unprocesed queue files + $qfiles = $this->getUnprocessedFileList(); + owa_coreAPI::notice('queue files to process: '.print_r($qfiles, true)); + // get earliest queue file based on creation time so we can process them in order + if ( $qfiles && is_array( $qfiles ) ) { + + return array_shift( $qfiles ); + + } else { + + return owa_coreAPI::notice('No unprocessed queue files to process.'); + } + } + + function getUnprocessedFileList() { + + $files = array(); + + $this->rotateEventFile(); + + if ( is_dir( $this->unprocessed_path ) ) { + foreach ( new DirectoryIterator( $this->unprocessed_path ) as $item ) { + if ( $item->isFile() && ! $item->isDot() ) { + $files[ $item->getMTime() ] = $item->getPathname(); + } + } + + // sort by key ascending + ksort( $files ); + } + + return $files; + } + + function pruneArchive( $interval ) { + + if ( is_dir( $this->archive_path ) ) { + + foreach ( new DirectoryIterator( $this->archive_path ) as $item ) { + + if ( $item->isFile() && + ! $item->isDot() && + $item->getMTime() < ( time() - $interval ) ) + { + owa_coreAPI::notice('about to unlink' . $item->getRealPath()); + $this->deleteFile( $item->getRealPath() ); + } + } + } + } + + function deleteFile( $path ) { + + return unlink( $path ); + } + + function rotateEventFile() { + + if ( file_exists( $this->event_file ) ) { + + // Create a new log file name + $new_file_path = sprintf("%s-eventfile-%s.txt", $this->unprocessed_path . $this->queue_name, date( $this->date_format ) ); + $ret = owa_lib::moveFile( $this->event_file, $new_file_path ); + + if ( $ret ) { + owa_coreAPI::debug('Rotated event file.'); + } else { + owa_coreAPI::debug('Could not rotate event file.'); + } + } + } + + function archiveProcessedFile( $file ) { + + $new_file_path = $this->archive_path . basename( $file ); + $ret = owa_lib::moveFile( $file, $new_file_path ); + } + + + function parse_log_row( $row ) { + + if ($row) { + $raw_event = explode("|*|", $row); + $row_array = array( 'timestamp' => $raw_event[0], 'event_obj' => $raw_event[3]); + $event = unserialize(urldecode($row_array['event_obj'])); + return $event; + } + } + + function create_lock_file() { + + $lock_file = fopen($this->lock_file, "w+") or die ("Could not create lock file at: ".$this->lock_file); + + // Write PID to lock file + if (fwrite($lock_file, getmypid()) === FALSE) { + owa_coreAPI::debug('Cannot write to lock file. Terminating Run.'); + exit; + } + } } ?> \ No newline at end of file diff --git a/modules/base/classes/geolocation.php b/modules/base/classes/geolocation.php index 145c43454..dd6a64925 100644 --- a/modules/base/classes/geolocation.php +++ b/modules/base/classes/geolocation.php @@ -24,126 +24,126 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 + * @version $Revision$ + * @since owa 1.3.0 */ class owa_geolocation { - var $properties = array(); - - public static function getInstance() { - - return new owa_geolocation(); - } + var $properties = array(); + + public static function getInstance() { + + return new owa_geolocation(); + } - function __construct() { - - } - - function __destruct() { - - } - - function getGeolocationFromIp($ip_address, $refresh = false) { - - if (empty($this->properties) || $refresh === true) { - - $geo = array('ip_address' => $ip_address, - 'city' => '', - 'country' => '', - 'state' => '', - 'country_code' => '', - 'latitude' => '', - 'longitude' => ''); - - if ( owa_coreAPI::getSetting( 'base', 'geolocation_lookup' ) ) { - - $eq = owa_coreAPI::getEventDispatch(); - $geo = $eq->filter('geolocation', $geo); - - } - - foreach ($geo as $k => $v) { - if ( ! $v ) { - $geo[$k] = '(not set)'; - } - } - - $this->properties = $geo; - } - } - - function getProperty($name) { - - if (array_key_exists($name, $this->properties)) { - return $this->properties[$name]; - } - } - - function setProperty($name, $value) { - - $this->properties[$name] = $value; - } - - function getCity() { - - if (array_key_exists('city', $this->properties)) { - return $this->properties['city']; - } - } - - function getState() { - if (array_key_exists('state', $this->properties)) { - return $this->properties['state']; - } - } - - function getCountry() { - if (array_key_exists('country', $this->properties)) { - return $this->properties['country']; - } - } - - function getCountryCode() { - if (array_key_exists('country_code', $this->properties)) { - return $this->properties['country_code']; - } - } - - function getLatitude() { - if (array_key_exists('latitude', $this->properties)) { - return $this->properties['latitude']; - } - } - - function getLongitude() { - if (array_key_exists('longitude', $this->properties)) { - return $this->properties['longitude']; - } - } - - function generateId($country = '', $state = '', $city = '') { - - if ( ! $country ) { - - $country = $this->getCountry(); - } - - if ( ! $state ) { - - $state = $this->getState(); - } - - if ( ! $city ) { - - $city = $this->getCity(); - } - $id_string = trim( strtolower($country)) . trim( strtolower($state)) . trim( strtolower($city)); - return owa_lib::setStringGuid( $id_string ); - - } + function __construct() { + + } + + function __destruct() { + + } + + function getGeolocationFromIp($ip_address, $refresh = false) { + + if (empty($this->properties) || $refresh === true) { + + $geo = array('ip_address' => $ip_address, + 'city' => '', + 'country' => '', + 'state' => '', + 'country_code' => '', + 'latitude' => '', + 'longitude' => ''); + + if ( owa_coreAPI::getSetting( 'base', 'geolocation_lookup' ) ) { + + $eq = owa_coreAPI::getEventDispatch(); + $geo = $eq->filter('geolocation', $geo); + + } + + foreach ($geo as $k => $v) { + if ( ! $v ) { + $geo[$k] = '(not set)'; + } + } + + $this->properties = $geo; + } + } + + function getProperty($name) { + + if (array_key_exists($name, $this->properties)) { + return $this->properties[$name]; + } + } + + function setProperty($name, $value) { + + $this->properties[$name] = $value; + } + + function getCity() { + + if (array_key_exists('city', $this->properties)) { + return $this->properties['city']; + } + } + + function getState() { + if (array_key_exists('state', $this->properties)) { + return $this->properties['state']; + } + } + + function getCountry() { + if (array_key_exists('country', $this->properties)) { + return $this->properties['country']; + } + } + + function getCountryCode() { + if (array_key_exists('country_code', $this->properties)) { + return $this->properties['country_code']; + } + } + + function getLatitude() { + if (array_key_exists('latitude', $this->properties)) { + return $this->properties['latitude']; + } + } + + function getLongitude() { + if (array_key_exists('longitude', $this->properties)) { + return $this->properties['longitude']; + } + } + + function generateId($country = '', $state = '', $city = '') { + + if ( ! $country ) { + + $country = $this->getCountry(); + } + + if ( ! $state ) { + + $state = $this->getState(); + } + + if ( ! $city ) { + + $city = $this->getCity(); + } + $id_string = trim( strtolower($country)) . trim( strtolower($state)) . trim( strtolower($city)); + return owa_lib::setStringGuid( $id_string ); + + } } ?> \ No newline at end of file diff --git a/modules/base/classes/goalManager.php b/modules/base/classes/goalManager.php index c60d4e5ad..cc2f33fd9 100644 --- a/modules/base/classes/goalManager.php +++ b/modules/base/classes/goalManager.php @@ -24,185 +24,185 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_goalManager extends owa_base { - var $goals; - var $activeGoals; - var $goal_group_labels; - var $activeGoalGroups; - var $activeGoalsByGroup; - var $site_id; - var $numGoals; - var $numGoalGroups; - var $isDirtyGoals; - var $isDirtyGoalGroups; - - /** - * Constructor - * - * Takes cache directory as param - * - * @param $cache_dir string - */ - function __construct( $site_id ) { - - $this->site_id = $site_id; - $this->numGoals = owa_coreAPI::getSetting('base', 'numGoals'); - $this->numGoalGroups = owa_coreAPI::getSetting('base', 'numGoalGroups'); - $this->loadGoals( $site_id ); - $this->loadGoalGroupLabels ( $site_id ); - } - - function setSiteId( $site_id ) { - - $this->site_id = $site_id; - } - - function loadGoalGroupLabels( $site_id ) { - - $this->goal_group_labels = array(); - for ( $i = 1; $i <= $this->numGoalGroups; $i++ ) { - $this->goal_group_labels[$i] = "Goal Group $i"; - } - - $from_db = owa_coreAPI::getSiteSetting( $site_id , 'goal_groups' ); - - if ($from_db) { - - foreach($from_db as $k => $goalGroup) { - if (array_key_exists($k, $this->goal_group_labels)) { - $this->goal_group_labels[$k] = $goalGroup; - } - } - } - } - - function loadGoals( $site_id ) { - - $this->goals = array(); - - for ( $i = 1; $i <= $this->numGoals; $i++ ) { - $this->goals[$i] = array( - 'goal_number' => '', - 'goal_name' => '', - 'goal_group' => '', - 'goal_status' => '', - 'goal_type' => '' - ); - } - - $from_db = owa_coreAPI::getSiteSetting( $site_id, 'goals' ); - - if ($from_db) { - - foreach ($from_db as $k => $goal) { - - if (array_key_exists($k, $this->goals)) { - // add to goal array - $this->goals[$k] = $goal; - // set active goal lists - if (array_key_exists('goal_status', $goal) && $goal['goal_status'] === 'active') { - // set active goals - $this->activeGoals[] = $goal['goal_number']; - // set active goal groups - if (array_key_exists('goal_group', $goal)) { - $this->activeGoalGroups[$goal['goal_group']] = $goal['goal_group']; - // set active goals by group - $this->activeGoalsByGroup[$goal['goal_group']][] = $goal['goal_number']; - } - } - } - } - } - } - - function getActiveGoals() { - if (!empty($this->activeGoals)) { - $goals = array(); - foreach ($this->activeGoals as $goal_number) { - $goals[$goal_number] = $this->getGoal($goal_number); - } - return $goals; - } - } - - function getAllGoals() { - - return $this->goals; - } - - function getActiveGoalGroups() { - - return $this->activeGoalGroups; - } - - function getActiveGoalsByGroup($group_number) { - - return $this->activeGoalsByGroup[$group_number]; - } - - function getGoal($number) { - - if ( array_key_exists( $number, $this->goals ) ) { - - return $this->goals[$number]; - } - } - - function getGoalGroupLabel($number) { - - if ( array_key_exists( $number, $this->goal_group_labels ) ) { - - return $this->goal_group_labels[$number]; - } - } - - function getAllGoalGroupLabels() { - - return $this->goal_group_labels; - } - - function saveGoal($number, $goal) { - - if ( $number <= $this->numGoals ) { - - $goal['goal_number'] = $number; - $this->goals[$goal['goal_number']] = $goal; - $this->isDirtyGoals = true; - } - } - - function saveGoalGroupLabel($number, $goal_group) { - - $this->goal_group_labels[$number] = $goal_group; - $this->isDirtyGoalGroups = true; - } - - function __destruct() { - - if ( $this->isDirtyGoals ) { - - owa_coreAPI::persistSiteSetting( $this->site_id, 'goals', $this->goals ); - } - - if ( $this->isDirtyGoalGroups ) { - - owa_coreAPI::persistSiteSetting( $this->site_id, 'goal_groups', $this->goal_group_labels ); - } - } - - function getGoalFunnel($goal_number) { - - $goal = $this->getGoal($goal_number); - if ( array_key_exists( 'details', $goal ) && array_key_exists( 'funnel_steps', $goal['details'] ) ) { - return $goal['details']['funnel_steps']; - } - } + var $goals; + var $activeGoals; + var $goal_group_labels; + var $activeGoalGroups; + var $activeGoalsByGroup; + var $site_id; + var $numGoals; + var $numGoalGroups; + var $isDirtyGoals; + var $isDirtyGoalGroups; + + /** + * Constructor + * + * Takes cache directory as param + * + * @param $cache_dir string + */ + function __construct( $site_id ) { + + $this->site_id = $site_id; + $this->numGoals = owa_coreAPI::getSetting('base', 'numGoals'); + $this->numGoalGroups = owa_coreAPI::getSetting('base', 'numGoalGroups'); + $this->loadGoals( $site_id ); + $this->loadGoalGroupLabels ( $site_id ); + } + + function setSiteId( $site_id ) { + + $this->site_id = $site_id; + } + + function loadGoalGroupLabels( $site_id ) { + + $this->goal_group_labels = array(); + for ( $i = 1; $i <= $this->numGoalGroups; $i++ ) { + $this->goal_group_labels[$i] = "Goal Group $i"; + } + + $from_db = owa_coreAPI::getSiteSetting( $site_id , 'goal_groups' ); + + if ($from_db) { + + foreach($from_db as $k => $goalGroup) { + if (array_key_exists($k, $this->goal_group_labels)) { + $this->goal_group_labels[$k] = $goalGroup; + } + } + } + } + + function loadGoals( $site_id ) { + + $this->goals = array(); + + for ( $i = 1; $i <= $this->numGoals; $i++ ) { + $this->goals[$i] = array( + 'goal_number' => '', + 'goal_name' => '', + 'goal_group' => '', + 'goal_status' => '', + 'goal_type' => '' + ); + } + + $from_db = owa_coreAPI::getSiteSetting( $site_id, 'goals' ); + + if ($from_db) { + + foreach ($from_db as $k => $goal) { + + if (array_key_exists($k, $this->goals)) { + // add to goal array + $this->goals[$k] = $goal; + // set active goal lists + if (array_key_exists('goal_status', $goal) && $goal['goal_status'] === 'active') { + // set active goals + $this->activeGoals[] = $goal['goal_number']; + // set active goal groups + if (array_key_exists('goal_group', $goal)) { + $this->activeGoalGroups[$goal['goal_group']] = $goal['goal_group']; + // set active goals by group + $this->activeGoalsByGroup[$goal['goal_group']][] = $goal['goal_number']; + } + } + } + } + } + } + + function getActiveGoals() { + if (!empty($this->activeGoals)) { + $goals = array(); + foreach ($this->activeGoals as $goal_number) { + $goals[$goal_number] = $this->getGoal($goal_number); + } + return $goals; + } + } + + function getAllGoals() { + + return $this->goals; + } + + function getActiveGoalGroups() { + + return $this->activeGoalGroups; + } + + function getActiveGoalsByGroup($group_number) { + + return $this->activeGoalsByGroup[$group_number]; + } + + function getGoal($number) { + + if ( array_key_exists( $number, $this->goals ) ) { + + return $this->goals[$number]; + } + } + + function getGoalGroupLabel($number) { + + if ( array_key_exists( $number, $this->goal_group_labels ) ) { + + return $this->goal_group_labels[$number]; + } + } + + function getAllGoalGroupLabels() { + + return $this->goal_group_labels; + } + + function saveGoal($number, $goal) { + + if ( $number <= $this->numGoals ) { + + $goal['goal_number'] = $number; + $this->goals[$goal['goal_number']] = $goal; + $this->isDirtyGoals = true; + } + } + + function saveGoalGroupLabel($number, $goal_group) { + + $this->goal_group_labels[$number] = $goal_group; + $this->isDirtyGoalGroups = true; + } + + function __destruct() { + + if ( $this->isDirtyGoals ) { + + owa_coreAPI::persistSiteSetting( $this->site_id, 'goals', $this->goals ); + } + + if ( $this->isDirtyGoalGroups ) { + + owa_coreAPI::persistSiteSetting( $this->site_id, 'goal_groups', $this->goal_group_labels ); + } + } + + function getGoalFunnel($goal_number) { + + $goal = $this->getGoal($goal_number); + if ( array_key_exists( 'details', $goal ) && array_key_exists( 'funnel_steps', $goal['details'] ) ) { + return $goal['details']['funnel_steps']; + } + } } ?> \ No newline at end of file diff --git a/modules/base/classes/hostip.php b/modules/base/classes/hostip.php index 686b50ea4..e9525f143 100644 --- a/modules/base/classes/hostip.php +++ b/modules/base/classes/hostip.php @@ -1,187 +1,187 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_hostip extends owa_location { - - /** - * URL template for REST based web service - * - * @var unknown_type - */ - var $ws_url = "http://api.hostip.info/get_html.php?ip=%s&position=true"; - - /** - * Constructor - * - * @return owa_hostip - */ - function __construct() { - - return parent::__construct(); - } - - /** - * Fetches the location from the hostip.info web service - * - * @param string $ip - */ - function get_location( $location_map ) { - - $city = ''; - $state = ''; - $country = ''; - $country_code = ''; - $latitude = ''; - $longitude = ''; - - // check to see if ip is in map - if ( array_key_exists('ip_address',$location_map) - && ! empty( $location_map['ip_address'] ) - && empty( $location_map['country'] ) ) { - - // check to see if ip is valid and not a private address - if ( filter_var( $location_map['ip_address'], - FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4 | - FILTER_FLAG_NO_PRIV_RANGE ) ) { - - // create crawler - $crawler = new owa_http; - $crawler->read_timeout = owa_coreAPI::getSetting('base','ws_timeout'); - // hit web service - $crawler->fetch(sprintf($this->ws_url, $location_map['ip_address'])); - owa_coreAPI::debug(sprintf("HostIp web service response code: %s", $crawler->crawler->response_code)); - $location = $crawler->crawler->results; - // replace delimiter - $location = str_replace("\n", "|", $location); - // convert string to array - $loc_array = explode("|", $location); - $result = array(); - // convert array to multi dimensional array - foreach ($loc_array as $k => $v) { - - if (!empty($v)) { - list($name, $value) = explode(":", $v, 2); - $result[$name] = $value; - } - } - - // parse the city line of response - if ( isset( $result['City'] ) && ! empty( $result['City'] ) ) { - // lowercase - $result['City'] = strtolower($result['City']); - // explode into array - $city_array = explode(',', $result['City']); - // city name is always first - $city = $city_array[0]; - // if there is a second element then it's a state - if (isset($city_array[1])) { - $state = $city_array[1]; - } - } - - // parse country line of response - if ( isset( $result['Country'] ) && ! empty( $result['Country'] ) ) { - //lowercase - $result['Country'] = strtolower( $result['Country'] ); - // set country - $country_parts = explode('(', trim( $result['Country'] ) ); - $country = $country_parts[0]; - // if there is a second element then it's a country code. - if ( isset($country_parts[1] ) ) { - $country_code = substr($country_parts[1],0,-1); - } - // debug - owa_coreAPI::debug('Parse of Hostip country string: '.$result['Country'].' c: '. $country.' cc: '.$country_code); - - } - - // set latitude - if ( isset( $result['Latitude'] ) && ! empty( $result['Latitude'] ) ) { - $latitude = $result['Latitude']; - } - // set longitude - if ( isset( $result['Longitude'] ) && ! empty( $result['Longitude'] ) ) { - $longitude = $result['Longitude']; - } - } - - // fail safe checks for empty, unknown or private adddress labels - // check to make sure values are not "private address" contain "unknown" or "xx" - if ( empty($city) || strpos( $city, 'private' ) || strpos( $city, 'unknown') ) { - - $city = '(not set)'; - } - // check state - if ( empty($state) || strpos( $state, 'private' ) || strpos( $state, 'unknown') ) { - - $state = '(not set)'; - } - // check country - if ( empty( $country ) - || strpos( $country, 'unknown' ) - || strpos( $country, 'private' ) - ) { - $country = '(not set)'; - } - // check country code - if ( empty( $country_code ) - || strpos( $country_code, 'xx' ) - || strpos( $country_code, 'unknown' ) - || strpos( $country_code, 'private' ) - ) { - $country_code = '(not set)'; - } - - $location_map['city'] = strtolower(trim($city)); - $location_map['state'] = strtolower(trim($state)); - $location_map['country'] = strtolower(trim($country)); - $location_map['country_code'] = strtoupper(trim($country_code)); - $location_map['latitude'] = trim($latitude); - $location_map['longitude'] = trim($longitude); - - // log headers if status is not a 200 - if ( isset( $crawler->response_code ) && ! strpos( $crawler->response_code, '200' ) ) { - owa_coreAPI::debug(sprintf("HostIp web service response headers: %s", print_r($crawler->crawler->headers, true))); - } - } - - return $location_map; - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_hostip extends owa_location { + + /** + * URL template for REST based web service + * + * @var unknown_type + */ + var $ws_url = "http://api.hostip.info/get_html.php?ip=%s&position=true"; + + /** + * Constructor + * + * @return owa_hostip + */ + function __construct() { + + return parent::__construct(); + } + + /** + * Fetches the location from the hostip.info web service + * + * @param string $ip + */ + function get_location( $location_map ) { + + $city = ''; + $state = ''; + $country = ''; + $country_code = ''; + $latitude = ''; + $longitude = ''; + + // check to see if ip is in map + if ( array_key_exists('ip_address',$location_map) + && ! empty( $location_map['ip_address'] ) + && empty( $location_map['country'] ) ) { + + // check to see if ip is valid and not a private address + if ( filter_var( $location_map['ip_address'], + FILTER_VALIDATE_IP, + FILTER_FLAG_IPV4 | + FILTER_FLAG_NO_PRIV_RANGE ) ) { + + // create crawler + $crawler = new owa_http; + $crawler->read_timeout = owa_coreAPI::getSetting('base','ws_timeout'); + // hit web service + $crawler->fetch(sprintf($this->ws_url, $location_map['ip_address'])); + owa_coreAPI::debug(sprintf("HostIp web service response code: %s", $crawler->crawler->response_code)); + $location = $crawler->crawler->results; + // replace delimiter + $location = str_replace("\n", "|", $location); + // convert string to array + $loc_array = explode("|", $location); + $result = array(); + // convert array to multi dimensional array + foreach ($loc_array as $k => $v) { + + if (!empty($v)) { + list($name, $value) = explode(":", $v, 2); + $result[$name] = $value; + } + } + + // parse the city line of response + if ( isset( $result['City'] ) && ! empty( $result['City'] ) ) { + // lowercase + $result['City'] = strtolower($result['City']); + // explode into array + $city_array = explode(',', $result['City']); + // city name is always first + $city = $city_array[0]; + // if there is a second element then it's a state + if (isset($city_array[1])) { + $state = $city_array[1]; + } + } + + // parse country line of response + if ( isset( $result['Country'] ) && ! empty( $result['Country'] ) ) { + //lowercase + $result['Country'] = strtolower( $result['Country'] ); + // set country + $country_parts = explode('(', trim( $result['Country'] ) ); + $country = $country_parts[0]; + // if there is a second element then it's a country code. + if ( isset($country_parts[1] ) ) { + $country_code = substr($country_parts[1],0,-1); + } + // debug + owa_coreAPI::debug('Parse of Hostip country string: '.$result['Country'].' c: '. $country.' cc: '.$country_code); + + } + + // set latitude + if ( isset( $result['Latitude'] ) && ! empty( $result['Latitude'] ) ) { + $latitude = $result['Latitude']; + } + // set longitude + if ( isset( $result['Longitude'] ) && ! empty( $result['Longitude'] ) ) { + $longitude = $result['Longitude']; + } + } + + // fail safe checks for empty, unknown or private adddress labels + // check to make sure values are not "private address" contain "unknown" or "xx" + if ( empty($city) || strpos( $city, 'private' ) || strpos( $city, 'unknown') ) { + + $city = '(not set)'; + } + // check state + if ( empty($state) || strpos( $state, 'private' ) || strpos( $state, 'unknown') ) { + + $state = '(not set)'; + } + // check country + if ( empty( $country ) + || strpos( $country, 'unknown' ) + || strpos( $country, 'private' ) + ) { + $country = '(not set)'; + } + // check country code + if ( empty( $country_code ) + || strpos( $country_code, 'xx' ) + || strpos( $country_code, 'unknown' ) + || strpos( $country_code, 'private' ) + ) { + $country_code = '(not set)'; + } + + $location_map['city'] = strtolower(trim($city)); + $location_map['state'] = strtolower(trim($state)); + $location_map['country'] = strtolower(trim($country)); + $location_map['country_code'] = strtoupper(trim($country_code)); + $location_map['latitude'] = trim($latitude); + $location_map['longitude'] = trim($longitude); + + // log headers if status is not a 200 + if ( isset( $crawler->response_code ) && ! strpos( $crawler->response_code, '200' ) ) { + owa_coreAPI::debug(sprintf("HostIp web service response headers: %s", print_r($crawler->crawler->headers, true))); + } + } + + return $location_map; + } +} + ?> \ No newline at end of file diff --git a/modules/base/classes/httpEventQueue.php b/modules/base/classes/httpEventQueue.php index bd7be9093..2ffa9bd00 100644 --- a/modules/base/classes/httpEventQueue.php +++ b/modules/base/classes/httpEventQueue.php @@ -26,60 +26,60 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_httpEventQueue extends owa_eventQueue { - - var $endpoint = ''; - - function __construct( $map = array() ) { - - if ( array_key_exists( 'endpoint', $map ) ) { - $this->endpoint = $map['endpoint']; - } else { - $this->endpoint = owa_coreAPI::getSetting('base', 'remote_event_queue_endpoint'); - } - - return parent::__construct( $map ); - } - - function sendMessage( $event ) { - - if ( $event ) { - - $properties = array(); - - $properties['owa_event'] = $event->export(); - - } else { - return; - } - - $parts = parse_url($this->endpoint); - - $fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 30); - - if (!$fp) { - return false; - } else { - - $content = http_build_query( $properties ); - - $out = "POST ".$parts['path']." HTTP/1.1\r\n"; - $out.= "Host: ".$parts['host']."\r\n"; - $out.= "Content-Type: application/x-www-form-urlencoded\r\n"; - $out.= "Content-Length: ".strlen( $content )."\r\n"; - $out.= "Connection: Close\r\n\r\n"; - $out.= $content; - - fwrite($fp, $out); - fclose($fp); - owa_coreAPI::debug("out: $out"); - return true; - } - } + + var $endpoint = ''; + + function __construct( $map = array() ) { + + if ( array_key_exists( 'endpoint', $map ) ) { + $this->endpoint = $map['endpoint']; + } else { + $this->endpoint = owa_coreAPI::getSetting('base', 'remote_event_queue_endpoint'); + } + + return parent::__construct( $map ); + } + + function sendMessage( $event ) { + + if ( $event ) { + + $properties = array(); + + $properties['owa_event'] = $event->export(); + + } else { + return; + } + + $parts = parse_url($this->endpoint); + + $fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 30); + + if (!$fp) { + return false; + } else { + + $content = http_build_query( $properties ); + + $out = "POST ".$parts['path']." HTTP/1.1\r\n"; + $out.= "Host: ".$parts['host']."\r\n"; + $out.= "Content-Type: application/x-www-form-urlencoded\r\n"; + $out.= "Content-Length: ".strlen( $content )."\r\n"; + $out.= "Connection: Close\r\n\r\n"; + $out.= $content; + + fwrite($fp, $out); + fclose($fp); + owa_coreAPI::debug("out: $out"); + return true; + } + } } ?> \ No newline at end of file diff --git a/modules/base/classes/installController.php b/modules/base/classes/installController.php index 4056380fc..2ec3e6e49 100644 --- a/modules/base/classes/installController.php +++ b/modules/base/classes/installController.php @@ -26,137 +26,137 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_installController extends owa_controller { - var $is_installer = true; - - function __construct($params) { - - // needed just in case a re-install happens and updates are also needed. - // tells the controller to skip the updates redirect - if (!defined('OWA_INSTALLING')) { - define('OWA_INSTALLING', true); - } - - //$this->c->setSetting('base', 'cache_objects', false); - - return parent::__construct($params); - } - - function pre() { - - if (owa_coreAPI::getSetting('base', 'install_complete')) { - owa_coreAPI::debug('Install complete redirecting to base.installDetected'); - return $this->redirectBrowser('base.installDetected', false); - } - - return; - } - - function installSchema() { - - $service = owa_coreAPI::serviceSingleton(); - $base = $service->getModule('base'); - $status = $base->install(); - return $status; - - } - - function createAdminUser($user_id, $email_address, $password = '') { - - //create user entity - $u = owa_coreAPI::entityFactory('base.user'); - // check to see if an admin user already exists - $u->getByColumn('role', 'admin'); - $id_check = $u->get('id'); - // if not then proceed - if (empty($id_check)) { - - //Check to see if user name already exists - $u->getByColumn('user_id', $user_id); - - $id = $u->get('id'); - - // Set user object Params - if (empty($id)) { - - // create random passsword if none provided. - if ( ! $password ) { - $password = $u->generateRandomPassword(); - } - $ret = $u->createNewUser($user_id, owa_user::ADMIN_USER_ROLE, $password, $email_address, owa_user::ADMIN_USER_REAL_NAME); - owa_coreAPI::debug("Admin user created successfully."); - return $password; - - } else { - owa_coreAPI::debug($this->getMsgAsString(3306)); - } - } else { - owa_coreAPI::debug("Admin user already exists."); - } - - } - - function createDefaultSite($domain, $name = '', $description = '', $site_family = '', $site_id = '') { - - if (!$name) { - $name = $domain; - } - - $site = owa_coreAPI::entityFactory('base.site'); - - if (!$site_id) { - $site_id = $site->generateSiteId($domain); - } - - - // Check to see if default site already exists - $this->e->notice('Checking for existence of default site.'); - - // create site_id....how??? - $site->getByColumn('site_id', $site_id); - $id = $site->get('id'); - - if(empty($id)) { - // Create default site - $site->set('id', $site->generateId($site_id)); - $site->set('site_id', $site_id); - $site->set('name', $name); - $site->set('description', $description); - $site->set('domain', $domain); - $site->set('site_family', $site_family); - $site_status = $site->create(); - - if ($site_status == true) { - $this->e->notice('Created default site.'); - } else { - $this->e->notice('Creation of default site failed.'); - } - - } else { - $this->e->notice(sprintf("Default site already exists (id = %s). nothing to do here.", $id)); - } - - return $site->get('site_id'); - } - - function checkDbConnection() { - - // Check DB connection status - $db = owa_coreAPI::dbSingleton(); - $db->connect(); - if ($db->connection_status === true) { - return true; - } else { - return false; - } - - } + var $is_installer = true; + + function __construct($params) { + + // needed just in case a re-install happens and updates are also needed. + // tells the controller to skip the updates redirect + if (!defined('OWA_INSTALLING')) { + define('OWA_INSTALLING', true); + } + + //$this->c->setSetting('base', 'cache_objects', false); + + return parent::__construct($params); + } + + function pre() { + + if (owa_coreAPI::getSetting('base', 'install_complete')) { + owa_coreAPI::debug('Install complete redirecting to base.installDetected'); + return $this->redirectBrowser('base.installDetected', false); + } + + return; + } + + function installSchema() { + + $service = owa_coreAPI::serviceSingleton(); + $base = $service->getModule('base'); + $status = $base->install(); + return $status; + + } + + function createAdminUser($user_id, $email_address, $password = '') { + + //create user entity + $u = owa_coreAPI::entityFactory('base.user'); + // check to see if an admin user already exists + $u->getByColumn('role', 'admin'); + $id_check = $u->get('id'); + // if not then proceed + if (empty($id_check)) { + + //Check to see if user name already exists + $u->getByColumn('user_id', $user_id); + + $id = $u->get('id'); + + // Set user object Params + if (empty($id)) { + + // create random passsword if none provided. + if ( ! $password ) { + $password = $u->generateRandomPassword(); + } + $ret = $u->createNewUser($user_id, owa_user::ADMIN_USER_ROLE, $password, $email_address, owa_user::ADMIN_USER_REAL_NAME); + owa_coreAPI::debug("Admin user created successfully."); + return $password; + + } else { + owa_coreAPI::debug($this->getMsgAsString(3306)); + } + } else { + owa_coreAPI::debug("Admin user already exists."); + } + + } + + function createDefaultSite($domain, $name = '', $description = '', $site_family = '', $site_id = '') { + + if (!$name) { + $name = $domain; + } + + $site = owa_coreAPI::entityFactory('base.site'); + + if (!$site_id) { + $site_id = $site->generateSiteId($domain); + } + + + // Check to see if default site already exists + $this->e->notice('Checking for existence of default site.'); + + // create site_id....how??? + $site->getByColumn('site_id', $site_id); + $id = $site->get('id'); + + if(empty($id)) { + // Create default site + $site->set('id', $site->generateId($site_id)); + $site->set('site_id', $site_id); + $site->set('name', $name); + $site->set('description', $description); + $site->set('domain', $domain); + $site->set('site_family', $site_family); + $site_status = $site->create(); + + if ($site_status == true) { + $this->e->notice('Created default site.'); + } else { + $this->e->notice('Creation of default site failed.'); + } + + } else { + $this->e->notice(sprintf("Default site already exists (id = %s). nothing to do here.", $id)); + } + + return $site->get('site_id'); + } + + function checkDbConnection() { + + // Check DB connection status + $db = owa_coreAPI::dbSingleton(); + $db->connect(); + if ($db->connection_status === true) { + return true; + } else { + return false; + } + + } } diff --git a/modules/base/classes/installManager.php b/modules/base/classes/installManager.php index 3fa1ac6bb..61500ded6 100644 --- a/modules/base/classes/installManager.php +++ b/modules/base/classes/installManager.php @@ -24,117 +24,117 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_installManager extends owa_base { - - function __construct($params = '') { - - return parent::__construct($params); - } - - function installSchema() { - - $service = owa_coreAPI::serviceSingleton(); - $base = $service->getModule('base'); - $status = $base->install(); - return $status; - - } - - function createAdminUser($user_id, $email_address, $password = '') { - - //create user entity - $u = owa_coreAPI::entityFactory('base.user'); - // check to see if an admin user already exists - $u->getByColumn('role', 'admin'); - $id_check = $u->get('id'); - // if not then proceed - if (empty($id_check)) { - - //Check to see if user name already exists - $u->getByColumn('user_id', $user_id); - - $id = $u->get('id'); - - // Set user object Params - if (empty($id)) { - - if ( ! $password ) { - - $password = $u->generateRandomPassword(); - } - - $ret = $u->createNewUser($user_id, owa_user::ADMIN_USER_ROLE, $password, $email_address, owa_user::ADMIN_USER_REAL_NAME); - owa_coreAPI::debug("Admin user created successfully."); - return $password; - - } else { - owa_coreAPI::debug($this->getMsgAsString(3306)); - } - } else { - owa_coreAPI::debug("Admin user already exists."); - } - - } - - function createDefaultSite($domain, $name = '', $description = '', $site_family = '', $site_id = '') { - - if (!$name) { - $name = $domain; - } - - $site = owa_coreAPI::entityFactory('base.site'); - - if (!$site_id) { - $site_id = $site->generateSiteId($domain); - } - - - // Check to see if default site already exists - $this->e->notice('Checking for existence of default site.'); - - // create site_id....how??? - $site->getByColumn('site_id', $site_id); - $id = $site->get('id'); - - if(empty($id)) { - // Create default site - $site->set('id', $site->generateId($site_id)); - $site->set('site_id', $site_id); - $site->set('name', $name); - $site->set('description', $description); - $site->set('domain', $domain); - $site->set('site_family', $site_family); - $site_status = $site->create(); - - if ($site_status == true) { - $this->e->notice('Created default site.'); - } else { - $this->e->notice('Creation of default site failed.'); - } - - } else { - $this->e->notice(sprintf("Default site already exists (id = %s). nothing to do here.", $id)); - } - - return $site->get('site_id'); - } - - function checkDbConnection() { - - // Check DB connection status - $db = owa_coreAPI::dbSingleton(); - $db->connect(); - if ($db->connection_status === true) { - return true; - } else { - return false; - } - } + + function __construct($params = '') { + + return parent::__construct($params); + } + + function installSchema() { + + $service = owa_coreAPI::serviceSingleton(); + $base = $service->getModule('base'); + $status = $base->install(); + return $status; + + } + + function createAdminUser($user_id, $email_address, $password = '') { + + //create user entity + $u = owa_coreAPI::entityFactory('base.user'); + // check to see if an admin user already exists + $u->getByColumn('role', 'admin'); + $id_check = $u->get('id'); + // if not then proceed + if (empty($id_check)) { + + //Check to see if user name already exists + $u->getByColumn('user_id', $user_id); + + $id = $u->get('id'); + + // Set user object Params + if (empty($id)) { + + if ( ! $password ) { + + $password = $u->generateRandomPassword(); + } + + $ret = $u->createNewUser($user_id, owa_user::ADMIN_USER_ROLE, $password, $email_address, owa_user::ADMIN_USER_REAL_NAME); + owa_coreAPI::debug("Admin user created successfully."); + return $password; + + } else { + owa_coreAPI::debug($this->getMsgAsString(3306)); + } + } else { + owa_coreAPI::debug("Admin user already exists."); + } + + } + + function createDefaultSite($domain, $name = '', $description = '', $site_family = '', $site_id = '') { + + if (!$name) { + $name = $domain; + } + + $site = owa_coreAPI::entityFactory('base.site'); + + if (!$site_id) { + $site_id = $site->generateSiteId($domain); + } + + + // Check to see if default site already exists + $this->e->notice('Checking for existence of default site.'); + + // create site_id....how??? + $site->getByColumn('site_id', $site_id); + $id = $site->get('id'); + + if(empty($id)) { + // Create default site + $site->set('id', $site->generateId($site_id)); + $site->set('site_id', $site_id); + $site->set('name', $name); + $site->set('description', $description); + $site->set('domain', $domain); + $site->set('site_family', $site_family); + $site_status = $site->create(); + + if ($site_status == true) { + $this->e->notice('Created default site.'); + } else { + $this->e->notice('Creation of default site failed.'); + } + + } else { + $this->e->notice(sprintf("Default site already exists (id = %s). nothing to do here.", $id)); + } + + return $site->get('site_id'); + } + + function checkDbConnection() { + + // Check DB connection status + $db = owa_coreAPI::dbSingleton(); + $db->connect(); + if ($db->connection_status === true) { + return true; + } else { + return false; + } + } } ?> \ No newline at end of file diff --git a/modules/base/classes/logConsole.php b/modules/base/classes/logConsole.php index d3e96320e..c4b8678d1 100644 --- a/modules/base/classes/logConsole.php +++ b/modules/base/classes/logConsole.php @@ -18,28 +18,28 @@ class owa_logConsole { - - var $name = 'generic_console_log'; - - function __construct( $conf = array() ) { - - if ( array_key_exists( 'name', $conf ) ) { - - $this->name = $conf['name']; - } - - } - - function append( $msg ) { - - if ( ! defined('STDOUT') ) { - - define('STDOUT', fopen("php://stdout", "w") ); - } - - fwrite( STDOUT, $msg ); - - } + + var $name = 'generic_console_log'; + + function __construct( $conf = array() ) { + + if ( array_key_exists( 'name', $conf ) ) { + + $this->name = $conf['name']; + } + + } + + function append( $msg ) { + + if ( ! defined('STDOUT') ) { + + define('STDOUT', fopen("php://stdout", "w") ); + } + + fwrite( STDOUT, $msg ); + + } } diff --git a/modules/base/classes/logEmail.php b/modules/base/classes/logEmail.php index 4a689d150..cdeaf8528 100644 --- a/modules/base/classes/logEmail.php +++ b/modules/base/classes/logEmail.php @@ -18,36 +18,36 @@ class owa_logEmail { - - var $name = 'generic_console_log'; - var $subject = 'uncaught exception'; - - function __construct( $conf = array() ) { - - if ( array_key_exists( 'name', $conf ) ) { - - $this->name = $conf['name']; - } - - if ( array_key_exists( 'subject', $conf ) ) { - - $this->subject = $conf['subject']; - } - - } - - function append( $msg ) { - - $address = owa_coreAPI::getSetting('base', 'notice_email'); - - $mailer = owa_coreAPI::supportClassFactory('base', 'mailer'); - $mailer->addAddress( $address, ''); - //$mailer->setFrom('owa@localhost', 'Open Web Analytics'); - $mailer->setSubject($this->subject); - $mailer->setHtmlBody( $msg ); - $mailer->send(); - - } + + var $name = 'generic_console_log'; + var $subject = 'uncaught exception'; + + function __construct( $conf = array() ) { + + if ( array_key_exists( 'name', $conf ) ) { + + $this->name = $conf['name']; + } + + if ( array_key_exists( 'subject', $conf ) ) { + + $this->subject = $conf['subject']; + } + + } + + function append( $msg ) { + + $address = owa_coreAPI::getSetting('base', 'notice_email'); + + $mailer = owa_coreAPI::supportClassFactory('base', 'mailer'); + $mailer->addAddress( $address, ''); + //$mailer->setFrom('owa@localhost', 'Open Web Analytics'); + $mailer->setSubject($this->subject); + $mailer->setHtmlBody( $msg ); + $mailer->send(); + + } } diff --git a/modules/base/classes/logFile.php b/modules/base/classes/logFile.php index f9f1ae7dc..ee3efb102 100644 --- a/modules/base/classes/logFile.php +++ b/modules/base/classes/logFile.php @@ -18,22 +18,22 @@ class owa_logFile { - - var $name = 'generic_log'; - var $file_path = ''; - - function __construct( $conf = array() ) { - - if ( array_key_exists( 'name', $conf ) ) { - $this->name = $conf['name']; - } - - if ( array_key_exists( 'file_path', $conf ) ) { - $this->file_path = $conf['file_path']; - } - } - - function append( $msg ) { + + var $name = 'generic_log'; + var $file_path = ''; + + function __construct( $conf = array() ) { + + if ( array_key_exists( 'name', $conf ) ) { + $this->name = $conf['name']; + } + + if ( array_key_exists( 'file_path', $conf ) ) { + $this->file_path = $conf['file_path']; + } + } + + function append( $msg ) { // no file path set stop execution if (!$this->file_path) { return; @@ -47,7 +47,7 @@ function append( $msg ) { $handle = fopen( $this->file_path , "a" ) or die('Could not open logfile: ' . $this->file_path); fwrite( $handle, $msg ); fclose( $handle ); - } + } } ?> \ No newline at end of file diff --git a/modules/base/classes/mailer.php b/modules/base/classes/mailer.php index a6633143d..032f6a061 100644 --- a/modules/base/classes/mailer.php +++ b/modules/base/classes/mailer.php @@ -1,135 +1,135 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_mailer extends owa_base { - - var $mailer; - - /** - * Constructor - * - * @return owa_mailer - * @throws \PHPMailer\PHPMailer\Exception - */ - function __construct() { - - parent::__construct(); - - $this->mailer = new PHPMailer(); - - if ( owa_coreAPI::getSetting( 'base', 'mailer-from' ) ) { - $this->mailer->setFrom(owa_coreAPI::getSetting( 'base', 'mailer-from' ), owa_coreAPI::getSetting( 'base', 'mailer-fromName' )); - } - - if ( owa_coreAPI::getSetting( 'base', 'mailer-use-smtp' ) ) { - - $this->mailer->IsSMTP(); // telling the class to use SMTP - - if ( owa_coreAPI::getSetting( 'base', 'mailer-host' ) ) { - - $this->mailer->Host = owa_coreAPI::getSetting( 'base', 'mailer-host' ); - } - - if ( owa_coreAPI::getSetting( 'base', 'mailer-port' ) ) { - - $this->mailer->Port = owa_coreAPI::getSetting( 'base', 'mailer-port' ); - } - - if ( owa_coreAPI::getSetting( 'base', 'mailer-smtpAuth' ) ) { - - $this->mailer->SMTPAuth = owa_coreAPI::getSetting( 'base', 'mailer-smtpAuth' ); - } - - if ( owa_coreAPI::getSetting( 'base', 'mailer-username') && owa_coreAPI::getSetting( 'base', 'mailer-password') ) { - - $this->mailer->Username = owa_coreAPI::getSetting( 'base', 'mailer-username'); - $this->mailer->Password = owa_coreAPI::getSetting( 'base', 'mailer-password'); - } - } - } - - function sendMail() { - - if( ! $this->mailer->send() ) { - return $this->e->debug(sprintf("Mailer Failure. Was not able to send with subject of '%s'. Error Msgs: '%s'", $this->mailer->Subject, $this->mailer->ErrorInfo)); - - } else { - return owa_coreAPI::debug( sprintf ("Mail sent with the subject of '%s'.", $this->mailer->Subject ) ); - } - } - - function send() { - - return $this->sendMail(); - } - - function addAddress( $address, $name ) { - - $this->mailer->addAddress( $address, $name ); - } - - function setFrom( $address, $name ) { - - $this->mailer->setFrom( $address, $name ); - } - - function setHtmlBody ( $html ) { - - $this->mailer->msgHTML( $html ); - } - - function setAltBody ( $text ) { - - $this->mailer->AltBody = $text; - } - - function setSubject( $subject ) { - - $this->mailer->Subject = $subject; - } - - function addReplyTo( $address, $name ) { - - $this->mailer->addReplyTo( $address, $name ); - } - - function addAttachment( $attachment ) { - - $this->mailer->addAttachment( $attachment ); - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_mailer extends owa_base { + + var $mailer; + + /** + * Constructor + * + * @return owa_mailer + * @throws \PHPMailer\PHPMailer\Exception + */ + function __construct() { + + parent::__construct(); + + $this->mailer = new PHPMailer(); + + if ( owa_coreAPI::getSetting( 'base', 'mailer-from' ) ) { + $this->mailer->setFrom(owa_coreAPI::getSetting( 'base', 'mailer-from' ), owa_coreAPI::getSetting( 'base', 'mailer-fromName' )); + } + + if ( owa_coreAPI::getSetting( 'base', 'mailer-use-smtp' ) ) { + + $this->mailer->IsSMTP(); // telling the class to use SMTP + + if ( owa_coreAPI::getSetting( 'base', 'mailer-host' ) ) { + + $this->mailer->Host = owa_coreAPI::getSetting( 'base', 'mailer-host' ); + } + + if ( owa_coreAPI::getSetting( 'base', 'mailer-port' ) ) { + + $this->mailer->Port = owa_coreAPI::getSetting( 'base', 'mailer-port' ); + } + + if ( owa_coreAPI::getSetting( 'base', 'mailer-smtpAuth' ) ) { + + $this->mailer->SMTPAuth = owa_coreAPI::getSetting( 'base', 'mailer-smtpAuth' ); + } + + if ( owa_coreAPI::getSetting( 'base', 'mailer-username') && owa_coreAPI::getSetting( 'base', 'mailer-password') ) { + + $this->mailer->Username = owa_coreAPI::getSetting( 'base', 'mailer-username'); + $this->mailer->Password = owa_coreAPI::getSetting( 'base', 'mailer-password'); + } + } + } + + function sendMail() { + + if( ! $this->mailer->send() ) { + return $this->e->debug(sprintf("Mailer Failure. Was not able to send with subject of '%s'. Error Msgs: '%s'", $this->mailer->Subject, $this->mailer->ErrorInfo)); + + } else { + return owa_coreAPI::debug( sprintf ("Mail sent with the subject of '%s'.", $this->mailer->Subject ) ); + } + } + + function send() { + + return $this->sendMail(); + } + + function addAddress( $address, $name ) { + + $this->mailer->addAddress( $address, $name ); + } + + function setFrom( $address, $name ) { + + $this->mailer->setFrom( $address, $name ); + } + + function setHtmlBody ( $html ) { + + $this->mailer->msgHTML( $html ); + } + + function setAltBody ( $text ) { + + $this->mailer->AltBody = $text; + } + + function setSubject( $subject ) { + + $this->mailer->Subject = $subject; + } + + function addReplyTo( $address, $name ) { + + $this->mailer->addReplyTo( $address, $name ); + } + + function addAttachment( $attachment ) { + + $this->mailer->addAttachment( $attachment ); + } + +} + ?> \ No newline at end of file diff --git a/modules/base/classes/memcachedCache.php b/modules/base/classes/memcachedCache.php index 8cdca2d97..6b0777dd3 100644 --- a/modules/base/classes/memcachedCache.php +++ b/modules/base/classes/memcachedCache.php @@ -19,7 +19,7 @@ require_once(OWA_BASE_CLASS_DIR.'cache.php'); if ( ! class_exists( 'memcached' ) ) { - require_once( OWA_INCLUDE_DIR . 'memcached-client.php' ); + require_once( OWA_INCLUDE_DIR . 'memcached-client.php' ); } /** @@ -30,114 +30,114 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_memcachedCache extends owa_cache { - var $mc; - - /** - * Constructor - * - * Takes cache directory as param - * - * @param $cache_dir string - */ - function __construct() { - - $servers = owa_coreAPI::getSetting( 'base', 'memcachedServers' ); - if ( ! $servers ) { - owa_coreAPI::notice('No memcached servers found in configuration settings.'); - return; - } - $persistant = owa_coreAPI::getSetting( 'base', 'memcachedPersistantConnections' ); - $error_mode = owa_coreAPI::getSetting( 'base', 'error_handler' ); - if ( $error_mode === 'development' ) { - $debug = true; - } else { - $debug = false; - } - - $this->mc = new owa_memcachedClient(array( - 'servers' => $servers, - 'debug' => $debug, - 'compress_threshold' => 10240, - 'persistant' => $persistant - )); - - return parent::__construct(); - } - - function makeKey($values) { - $key = 'owa-'; - $key .= $this->cache_id . '-'; - $key .= implode('-', $values); - return $key; - } - - function getItemFromCacheStore($collection, $id) { - $key = $this->makeKey( array( $collection, $id ) ); - $item = $this->mc->get( $key ); - - if ($item) { - $this->debug("$key retrieved from memcache."); - return $item; - } else { - $this->debug("$key was not found in memcache."); - } - - } - - function putItemToCacheStore($collection, $id) { - - $key = $this->makeKey( array( $collection, $id ) ); - $item = $this->cache[$collection][$id]; - $expiration = $this->getCollectionExpirationPeriod( $collection ); - $ret = $this->mc->replace( $key, $item, $expiration ); - - if ( $ret ) { - $this->debug( "$key successfully replaced in memcache." ); - return true; - - } else { - $ret = $this->mc->add( $key, $item ); - if ( $ret ) { - $this->debug( "$key successfully added to memcache." ); - return true; - } else { - $this->debug( "$key not added/replaced in memcache." ); - return false; - } - } - } - - function removeItemFromCacheStore($collection, $id) { - - $key = $this->makeKey( array( $collection, $id ) ); - $item = $this->cache[$collection][$id]; - $ret = $this->mc->delete($key); - - if ($ret) { - $this->debug( "$key successfully deleted from memcache." ); - } else { - $this->debug( "$key not deleted from memcache."); - } - } - - function flush() { - - owa_coreAPI::notice("Cannot flush Memcache from client."); - return true; - } + var $mc; + + /** + * Constructor + * + * Takes cache directory as param + * + * @param $cache_dir string + */ + function __construct() { + + $servers = owa_coreAPI::getSetting( 'base', 'memcachedServers' ); + if ( ! $servers ) { + owa_coreAPI::notice('No memcached servers found in configuration settings.'); + return; + } + $persistant = owa_coreAPI::getSetting( 'base', 'memcachedPersistantConnections' ); + $error_mode = owa_coreAPI::getSetting( 'base', 'error_handler' ); + if ( $error_mode === 'development' ) { + $debug = true; + } else { + $debug = false; + } + + $this->mc = new owa_memcachedClient(array( + 'servers' => $servers, + 'debug' => $debug, + 'compress_threshold' => 10240, + 'persistant' => $persistant + )); + + return parent::__construct(); + } + + function makeKey($values) { + $key = 'owa-'; + $key .= $this->cache_id . '-'; + $key .= implode('-', $values); + return $key; + } + + function getItemFromCacheStore($collection, $id) { + $key = $this->makeKey( array( $collection, $id ) ); + $item = $this->mc->get( $key ); + + if ($item) { + $this->debug("$key retrieved from memcache."); + return $item; + } else { + $this->debug("$key was not found in memcache."); + } + + } + + function putItemToCacheStore($collection, $id) { + + $key = $this->makeKey( array( $collection, $id ) ); + $item = $this->cache[$collection][$id]; + $expiration = $this->getCollectionExpirationPeriod( $collection ); + $ret = $this->mc->replace( $key, $item, $expiration ); + + if ( $ret ) { + $this->debug( "$key successfully replaced in memcache." ); + return true; + + } else { + $ret = $this->mc->add( $key, $item ); + if ( $ret ) { + $this->debug( "$key successfully added to memcache." ); + return true; + } else { + $this->debug( "$key not added/replaced in memcache." ); + return false; + } + } + } + + function removeItemFromCacheStore($collection, $id) { + + $key = $this->makeKey( array( $collection, $id ) ); + $item = $this->cache[$collection][$id]; + $ret = $this->mc->delete($key); + + if ($ret) { + $this->debug( "$key successfully deleted from memcache." ); + } else { + $this->debug( "$key not deleted from memcache."); + } + } + + function flush() { + + owa_coreAPI::notice("Cannot flush Memcache from client."); + return true; + } } class owa_memcachedClient extends memcached { - - function _debugprint( $text ) { - owa_coreAPI::debug( "memcached: $text" ); - } + + function _debugprint( $text ) { + owa_coreAPI::debug( "memcached: $text" ); + } } ?> diff --git a/modules/base/classes/paginatedResultSet.php b/modules/base/classes/paginatedResultSet.php index f97de4061..c0bad8fe8 100644 --- a/modules/base/classes/paginatedResultSet.php +++ b/modules/base/classes/paginatedResultSet.php @@ -24,375 +24,375 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_paginatedResultSet { - /** - * Unique hash of result set used by front end - * to see if there are any changes. - */ - var $guid; - - var $timePeriod; - var $resultsPerPage = 25; - var $resultsTotal; - var $resultsReturned; - var $resultsRows = array(); - var $sortColumn; - var $sortOrder; - - /** - * Aggregate values for metrics - */ - var $aggregates = array(); - - var $rows; - - var $labels; - - var $more; - var $page = 1; - var $total_pages; - - /** - * The API URL that produces the results - */ - var $self; - - /** - * The API URL that produces the next page of results - */ - var $next; - - /** - * The API URL that produces the previous page of results - */ - var $previous; - - /** - * The base API URL that is used to construct client side pagination links. - * Does not contain any 'page' params. - */ - var $base_url; - - /** - * The list of related dimensions that can be added to the result set - * - */ - var $relatedDimensions = array(); - - /** - * The list of related metrics that can be added to the result set - * - */ - var $relatedMetrics = array(); - - var $results_count = 0; - var $offset = 0; - var $limit; - var $query_limit; - - - function __construct() { - - } - - function setLimit($limit) { - - $this->resultsPerPage = $limit; - $this->limit = $limit; - } - - function setPage($page) { - - $this->page = $page; - } - - function setMorePages() { - - $this->more = true; - } - - function calculateOffset() { - - $this->offset = $this->limit * ($this->page - 1); - return $this->offset; - } - - function countResults($results) { - - $this->resultsTotal = count($results); - $this->results_count = count($results); - - if ($this->limit) { - $this->total_pages = ceil(($this->results_count + $this->offset) / $this->limit); - - if ($this->results_count <= $this->limit) { - // no more pages - } else { - // more pages - $this->setMorePages(); - - } - } - } - - function getRowCount() { - - return $this->results_count; - } - - function generate($dao, $method = 'getAllRows') { - - if (!empty($this->limit)) { - // query for more than we need - owa_coreAPI::debug('applying limit of: '.$this->limit); - $dao->limit($this->limit * 10); - } - - if (!empty($this->page)) { - - $dao->offset($this->calculateOffset()); - } else { - $this->page = 1; - } - - $results = $dao->$method(); - if (!empty($results)) { - $this->countResults($results); - - if ($this->resultsPerPage) { - $this->rows = array_slice($results, 0, $this->limit); - } else { - $this->rows = $results; - } - - $this->resultsReturned = count($this->rows); - } else { - $this->rows = array(); - } - - return $this->rows; - } - - function getResultSetAsArray() { - - $set = array(); - - $set['labels'] = $this->labels; - $set['rows'] = $this->rows; - $set['count'] = $this->results_count; - $set['page'] = $this->page; - $set['total_pages'] = $this->total_pages; - $set['more'] = $this->more; - $set['period'] = $this->getPeriodInfo(); - return $set; - } - - function setLabels($labels) { - - $this->labels = $labels; - } - - function displayPagination() { - - - } - - function getPeriodInfo() { - return $this->periodInfo; - } - - function setPeriodInfo($info) { - $this->timePeriod = $info; - } - - function getLabel($key) { - - if (array_key_exists($key, $this->labels)) { - return $this->labels[$key]; - } - } - - function getAllLabels() { - - return $this->labels; - } - - - function formatResults( $format ) { - - $formats = array('html' => 'resultSetToHtml', - 'json' => 'resultSetToJson', - 'jsonp' => 'resultSetToJsonp', - 'xml' => 'resultSetToXml', - 'php' => 'resultSetToSerializedPhp', - 'csv' => 'resultSetToCsv', - 'debug' => 'resultSetToDebug'); - - if ( array_key_exists( $format, $formats ) ) { - - $method = $formats[ $format ]; - - return $this->$method(); - - } else { - - owa_coreAPI::debug("Format '$format' is not supported."); - return $this; - } - } - - // @todo move this to a proper xml view - function resultSetToXml() { - - $t = new owa_template; - - $t->set_template('resultSetXml.php'); - $t->set('rs', $this); - - return $t->fetch(); - } - - //json formatting has been moved to owa_jsonView - function resultSetToJson() { - - return $this; - } - - //json formatting has been moved to owa_jsonView - function resultSetToJsonp($callback = '') { - - return $this; - } - - function resultSetToDebug() { - - return print_r($this, true); - } - - function resultSetToSerializedPhp() { - return serialize($this); - } - - function resultSetToHtml($class = 'dimensionalResultSet') { - $t = new owa_template; - - $t->set_template('resultSetHtml.php'); - $t->set('rs', $this); - $t->set('class', $class); - - return $t->fetch(); - } - - function getDataRows() { - return $this->resultsRows; - } - - function getResultsRows() { - return $this->resultsRows; - } - - function addLinkToRowItem($item_name, $template, $subs) { - - - foreach ($this->resultsRows as $k => $row) { - - $sub_array = array(); - - foreach ($subs as $sub) { - $sub_array[] = urlencode($this->resultsRows[$k][$sub]['value']); - } - - $this->resultsRows[$k][$item_name]['link'] = vsprintf($template, $sub_array); - } - - } - - function getSeries($name) { - - $rows = $this->getDataRows(); - - if ($rows) { - $series = array(); - foreach ($rows as $row) { - foreach($row as $item) { - if ($item['name'] === $name) { - $series[] = $item['value']; - } - } - } - return $series; - } else { - return false; - } - } - - function getAggregateMetric($name) { - - if ( array_key_exists( $name, $this->aggregates ) ) { - return $this->aggregates[$name]['value']; - } else { - owa_coreAPI::debug( "No aggregate metric called $name found." ); - } - } - - function setAggregateMetric($name, $value, $label, $data_type, $formatted_value = '') { - - $this->aggregates[$name] = array('result_type' => 'metric', 'name' => $name, 'value' => $value, 'label' => $label, 'data_type' => $data_type, 'formatted_value' => $formatted_value); - } - - function appendRow($row_num, $type, $name, $value, $label, $data_type, $formatted_value = '') { - - $this->resultsRows[$row_num][$name] = array( - 'result_type' => $type, - 'name' => $name, - 'value' => $value, - 'label' => $label, - 'data_type' => $data_type, - 'formatted_value' => $formatted_value - ); - } - - function removeMetric($name) { - - if (array_key_exists($name, $this->aggregates)) { - - unset($this->aggregates[$name]); - } - - if ($this->getRowCount() > 0) { - - foreach ($this->resultsRows as $k => $row) { - - if (array_key_exists($name, $row)) { - - unset($this->resultsRows[$k][$name]); - } - } - } - } - - function createResultSetHash() { - - $this->guid = md5(serialize($this)); - } - - function setRelatedDimensions( $dims = '' ) { - - if ( $dims ) { - $this->relatedDimensions = $dims; - } - } - - function setRelatedMetrics( $metrics = '' ) { - - if ( $metrics ) { - $this->relatedMetrics = $metrics; - } - } + /** + * Unique hash of result set used by front end + * to see if there are any changes. + */ + var $guid; + + var $timePeriod; + var $resultsPerPage = 25; + var $resultsTotal; + var $resultsReturned; + var $resultsRows = array(); + var $sortColumn; + var $sortOrder; + + /** + * Aggregate values for metrics + */ + var $aggregates = array(); + + var $rows; + + var $labels; + + var $more; + var $page = 1; + var $total_pages; + + /** + * The API URL that produces the results + */ + var $self; + + /** + * The API URL that produces the next page of results + */ + var $next; + + /** + * The API URL that produces the previous page of results + */ + var $previous; + + /** + * The base API URL that is used to construct client side pagination links. + * Does not contain any 'page' params. + */ + var $base_url; + + /** + * The list of related dimensions that can be added to the result set + * + */ + var $relatedDimensions = array(); + + /** + * The list of related metrics that can be added to the result set + * + */ + var $relatedMetrics = array(); + + var $results_count = 0; + var $offset = 0; + var $limit; + var $query_limit; + + + function __construct() { + + } + + function setLimit($limit) { + + $this->resultsPerPage = $limit; + $this->limit = $limit; + } + + function setPage($page) { + + $this->page = $page; + } + + function setMorePages() { + + $this->more = true; + } + + function calculateOffset() { + + $this->offset = $this->limit * ($this->page - 1); + return $this->offset; + } + + function countResults($results) { + + $this->resultsTotal = count($results); + $this->results_count = count($results); + + if ($this->limit) { + $this->total_pages = ceil(($this->results_count + $this->offset) / $this->limit); + + if ($this->results_count <= $this->limit) { + // no more pages + } else { + // more pages + $this->setMorePages(); + + } + } + } + + function getRowCount() { + + return $this->results_count; + } + + function generate($dao, $method = 'getAllRows') { + + if (!empty($this->limit)) { + // query for more than we need + owa_coreAPI::debug('applying limit of: '.$this->limit); + $dao->limit($this->limit * 10); + } + + if (!empty($this->page)) { + + $dao->offset($this->calculateOffset()); + } else { + $this->page = 1; + } + + $results = $dao->$method(); + if (!empty($results)) { + $this->countResults($results); + + if ($this->resultsPerPage) { + $this->rows = array_slice($results, 0, $this->limit); + } else { + $this->rows = $results; + } + + $this->resultsReturned = count($this->rows); + } else { + $this->rows = array(); + } + + return $this->rows; + } + + function getResultSetAsArray() { + + $set = array(); + + $set['labels'] = $this->labels; + $set['rows'] = $this->rows; + $set['count'] = $this->results_count; + $set['page'] = $this->page; + $set['total_pages'] = $this->total_pages; + $set['more'] = $this->more; + $set['period'] = $this->getPeriodInfo(); + return $set; + } + + function setLabels($labels) { + + $this->labels = $labels; + } + + function displayPagination() { + + + } + + function getPeriodInfo() { + return $this->periodInfo; + } + + function setPeriodInfo($info) { + $this->timePeriod = $info; + } + + function getLabel($key) { + + if (array_key_exists($key, $this->labels)) { + return $this->labels[$key]; + } + } + + function getAllLabels() { + + return $this->labels; + } + + + function formatResults( $format ) { + + $formats = array('html' => 'resultSetToHtml', + 'json' => 'resultSetToJson', + 'jsonp' => 'resultSetToJsonp', + 'xml' => 'resultSetToXml', + 'php' => 'resultSetToSerializedPhp', + 'csv' => 'resultSetToCsv', + 'debug' => 'resultSetToDebug'); + + if ( array_key_exists( $format, $formats ) ) { + + $method = $formats[ $format ]; + + return $this->$method(); + + } else { + + owa_coreAPI::debug("Format '$format' is not supported."); + return $this; + } + } + + // @todo move this to a proper xml view + function resultSetToXml() { + + $t = new owa_template; + + $t->set_template('resultSetXml.php'); + $t->set('rs', $this); + + return $t->fetch(); + } + + //json formatting has been moved to owa_jsonView + function resultSetToJson() { + + return $this; + } + + //json formatting has been moved to owa_jsonView + function resultSetToJsonp($callback = '') { + + return $this; + } + + function resultSetToDebug() { + + return print_r($this, true); + } + + function resultSetToSerializedPhp() { + return serialize($this); + } + + function resultSetToHtml($class = 'dimensionalResultSet') { + $t = new owa_template; + + $t->set_template('resultSetHtml.php'); + $t->set('rs', $this); + $t->set('class', $class); + + return $t->fetch(); + } + + function getDataRows() { + return $this->resultsRows; + } + + function getResultsRows() { + return $this->resultsRows; + } + + function addLinkToRowItem($item_name, $template, $subs) { + + + foreach ($this->resultsRows as $k => $row) { + + $sub_array = array(); + + foreach ($subs as $sub) { + $sub_array[] = urlencode($this->resultsRows[$k][$sub]['value']); + } + + $this->resultsRows[$k][$item_name]['link'] = vsprintf($template, $sub_array); + } + + } + + function getSeries($name) { + + $rows = $this->getDataRows(); + + if ($rows) { + $series = array(); + foreach ($rows as $row) { + foreach($row as $item) { + if ($item['name'] === $name) { + $series[] = $item['value']; + } + } + } + return $series; + } else { + return false; + } + } + + function getAggregateMetric($name) { + + if ( array_key_exists( $name, $this->aggregates ) ) { + return $this->aggregates[$name]['value']; + } else { + owa_coreAPI::debug( "No aggregate metric called $name found." ); + } + } + + function setAggregateMetric($name, $value, $label, $data_type, $formatted_value = '') { + + $this->aggregates[$name] = array('result_type' => 'metric', 'name' => $name, 'value' => $value, 'label' => $label, 'data_type' => $data_type, 'formatted_value' => $formatted_value); + } + + function appendRow($row_num, $type, $name, $value, $label, $data_type, $formatted_value = '') { + + $this->resultsRows[$row_num][$name] = array( + 'result_type' => $type, + 'name' => $name, + 'value' => $value, + 'label' => $label, + 'data_type' => $data_type, + 'formatted_value' => $formatted_value + ); + } + + function removeMetric($name) { + + if (array_key_exists($name, $this->aggregates)) { + + unset($this->aggregates[$name]); + } + + if ($this->getRowCount() > 0) { + + foreach ($this->resultsRows as $k => $row) { + + if (array_key_exists($name, $row)) { + + unset($this->resultsRows[$k][$name]); + } + } + } + } + + function createResultSetHash() { + + $this->guid = md5(serialize($this)); + } + + function setRelatedDimensions( $dims = '' ) { + + if ( $dims ) { + $this->relatedDimensions = $dims; + } + } + + function setRelatedMetrics( $metrics = '' ) { + + if ( $metrics ) { + $this->relatedMetrics = $metrics; + } + } } ?> \ No newline at end of file diff --git a/modules/base/classes/pagination.php b/modules/base/classes/pagination.php index f93c96834..9904c96ce 100644 --- a/modules/base/classes/pagination.php +++ b/modules/base/classes/pagination.php @@ -24,89 +24,89 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_pagination extends owa_base { - var $page = 1; - - var $limit; - - var $offset = 0; - - var $total_count; - - function __construct() { - - return; - - } - - function setLimit($limit) { - $this->limit = $limit; - return; - } - - function setPage($page) { - $this->page = $page; - return; - } - - function setMorePages($bool) { - - $this->more_pages = $bool; - return; - - } - - function calculateOffset() { - - $this->offset = $this->limit * ($this->page - 1); - return $this->offset; - } - - function getMaxPageNum() { - - if ($this->total_count > 0) { - - $c = $this->total_count / $this->limit; - $c = ceil($c); - } else { - - $c = 0; - } - - return $c; - } - - function getPagination() { - - $pagination = array(); - $pagination['limit'] = $this->limit; - $pagination['page_num'] = $this->page; - $pagination['offset'] = $this->offset; - $pagination['max_page_num'] = $this->getMaxPageNum(); - $pagination['more_pages'] = $this->more_pages; - $pagination['total_count'] = $this->total_count; - $pagination['results_count'] = $this->results_count; - $pagination['diff_count'] = $this->total_count - $this->results_count; - return $pagination; - } - - function countResults($results) { - - $this->results_count = count($results); - - if ($this->results_count < $this->limit): - $this->more_pages = false; - else: - $this->more_pages = true; - endif; - - return; - } - + var $page = 1; + + var $limit; + + var $offset = 0; + + var $total_count; + + function __construct() { + + return; + + } + + function setLimit($limit) { + $this->limit = $limit; + return; + } + + function setPage($page) { + $this->page = $page; + return; + } + + function setMorePages($bool) { + + $this->more_pages = $bool; + return; + + } + + function calculateOffset() { + + $this->offset = $this->limit * ($this->page - 1); + return $this->offset; + } + + function getMaxPageNum() { + + if ($this->total_count > 0) { + + $c = $this->total_count / $this->limit; + $c = ceil($c); + } else { + + $c = 0; + } + + return $c; + } + + function getPagination() { + + $pagination = array(); + $pagination['limit'] = $this->limit; + $pagination['page_num'] = $this->page; + $pagination['offset'] = $this->offset; + $pagination['max_page_num'] = $this->getMaxPageNum(); + $pagination['more_pages'] = $this->more_pages; + $pagination['total_count'] = $this->total_count; + $pagination['results_count'] = $this->results_count; + $pagination['diff_count'] = $this->total_count - $this->results_count; + return $pagination; + } + + function countResults($results) { + + $this->results_count = count($results); + + if ($this->results_count < $this->limit): + $this->more_pages = false; + else: + $this->more_pages = true; + endif; + + return; + } + } diff --git a/modules/base/classes/pslReader.php b/modules/base/classes/pslReader.php index 207b5ea72..d9a288101 100644 --- a/modules/base/classes/pslReader.php +++ b/modules/base/classes/pslReader.php @@ -29,80 +29,80 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.5.3 + * @version $Revision$ + * @since owa 1.5.3 */ class owa_pslReader { - var $tldTree = array(); - - public function __construct() { - - // Load browscap file into memory - $tld_file = OWA_DATA_DIR.'public_suffix_list/effectiveTLDs.inc.php'; - // check to see if a user downloaded version of the file exists - if ( ! file_exists( $tld_file ) ) { - $tld_file = OWA_BASE_MODULE_DIR.'data/effectiveTLDs.inc.php'; - } - - include_once( $tld_file ); - - $this->tldTree = $tldTree; - unset($tldTree); - } - - /* - * Remove subdomains from a signing domain to get the registered domain. - * - * dkim-reputation.org blocks signing domains on the level of registered domains - * to rate senders who use e.g. a.spamdomain.tld, b.spamdomain.tld, ... under - * the most common identifier - the registered domain - finally. - * - * This function returns NULL if $signingDomain is TLD itself - */ - public function getRegisteredDomain( $signingDomain ) { - - $signingDomainParts = explode( '.', $signingDomain ); - - $result = $this->findRegisteredDomain( $signingDomainParts, $this->tldTree ); - - if ($result===NULL || $result=="") { - // this is an invalid domain name - return NULL; - } - - // assure there is at least 1 TLD in the stripped signing domain - if (!strpos($result, '.')) { - $cnt = count($signingDomainParts); - if ($cnt==1 || $signingDomainParts[$cnt-2]=="") return NULL; - return $signingDomainParts[$cnt-2].'.'.$signingDomainParts[$cnt-1]; - } - return $result; - } - - // recursive helper method - private function findRegisteredDomain($remainingSigningDomainParts, &$treeNode) { - - $sub = array_pop($remainingSigningDomainParts); - - $result = NULL; - if (isset($treeNode['!'])) { - return '#'; - } else if (is_array($treeNode) && array_key_exists($sub, $treeNode)) { - $result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode[$sub]); - } else if (is_array($treeNode) && array_key_exists('*', $treeNode)) { - $result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode['*']); - } else { - return $sub; - } - - // this is a hack 'cause PHP interpretes '' as NULL - if ($result == '#') { - return $sub; - } else if (strlen($result)>0) { - return $result.'.'.$sub; - } - return NULL; - } + var $tldTree = array(); + + public function __construct() { + + // Load browscap file into memory + $tld_file = OWA_DATA_DIR.'public_suffix_list/effectiveTLDs.inc.php'; + // check to see if a user downloaded version of the file exists + if ( ! file_exists( $tld_file ) ) { + $tld_file = OWA_BASE_MODULE_DIR.'data/effectiveTLDs.inc.php'; + } + + include_once( $tld_file ); + + $this->tldTree = $tldTree; + unset($tldTree); + } + + /* + * Remove subdomains from a signing domain to get the registered domain. + * + * dkim-reputation.org blocks signing domains on the level of registered domains + * to rate senders who use e.g. a.spamdomain.tld, b.spamdomain.tld, ... under + * the most common identifier - the registered domain - finally. + * + * This function returns NULL if $signingDomain is TLD itself + */ + public function getRegisteredDomain( $signingDomain ) { + + $signingDomainParts = explode( '.', $signingDomain ); + + $result = $this->findRegisteredDomain( $signingDomainParts, $this->tldTree ); + + if ($result===NULL || $result=="") { + // this is an invalid domain name + return NULL; + } + + // assure there is at least 1 TLD in the stripped signing domain + if (!strpos($result, '.')) { + $cnt = count($signingDomainParts); + if ($cnt==1 || $signingDomainParts[$cnt-2]=="") return NULL; + return $signingDomainParts[$cnt-2].'.'.$signingDomainParts[$cnt-1]; + } + return $result; + } + + // recursive helper method + private function findRegisteredDomain($remainingSigningDomainParts, &$treeNode) { + + $sub = array_pop($remainingSigningDomainParts); + + $result = NULL; + if (isset($treeNode['!'])) { + return '#'; + } else if (is_array($treeNode) && array_key_exists($sub, $treeNode)) { + $result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode[$sub]); + } else if (is_array($treeNode) && array_key_exists('*', $treeNode)) { + $result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode['*']); + } else { + return $sub; + } + + // this is a hack 'cause PHP interpretes '' as NULL + if ($result == '#') { + return $sub; + } else if (strlen($result)>0) { + return $result.'.'.$sub; + } + return NULL; + } } ?> \ No newline at end of file diff --git a/modules/base/classes/resultSetManager.php b/modules/base/classes/resultSetManager.php index 64822b636..973c293b6 100644 --- a/modules/base/classes/resultSetManager.php +++ b/modules/base/classes/resultSetManager.php @@ -30,1735 +30,1735 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 + * @version $Revision$ + * @since owa 1.3.0 */ class owa_resultSetManager extends owa_base { - /** - * The params of the caller, either a report or graph - * - * @var array - */ - var $params = array(); - - /** - * The lables for calculated measures - * - * @var array - */ - var $labels = array(); - - /** - * Data Access Object - * - * @var object - */ - var $db; - - /** - * The dimensions to groupby - * - * @var array - */ - var $dimensions = array(); - - /** - * The Number of Dimensions to groupby - * - * @var integer - */ - var $dimensionCount; - - /** - * The table/column or denormalized dimensions - * associated with this metric - * - * @var array - */ - var $denormalizedDimensions = array(); - - var $_default_offset = 0; - var $page; - var $limit; - var $order; - var $format; - var $constraint_operators = array('==','!=','>=', '<=', '>', '<', '=~', '!~', '=@','!@'); - var $related_entities = array(); - var $related_dimensions = array(); - var $related_metrics = array(); - var $resultSet; - var $base_table; - var $metrics = array(); - var $metricsByTable = array(); - var $childMetrics = array(); - var $calculatedMetrics = array(); - var $query_params = array(); - var $baseEntity; - var $metricObjectsByEntityMap = array(); - var $metricObjectsCache = array(); - var $errors = array(); - var $formatters = array(); - var $segment; - - function __construct($db = '') { - - if ($db) { - $this->db = $db; - } else { - $this->db = owa_coreAPI::dbSingleton(); - } - - $this->formatters = array( - //'yyyymmdd' => array($this, 'dateFormatter'), - 'timestamp' => array($this, 'formatSeconds'), - 'percentage' => array($this, 'formatPercentage'), - 'integer' => array($this, 'numberFormatter'), - 'currency' => array($this, 'formatCurrency') - ); - - return parent::__construct(); - } - - - function setConstraint($name, $value, $operator = '') { - - if (empty($operator)) { - $operator = '='; - } - - if ( ! owa_lib::isEmpty( $value ) ) { - $this->params['constraints'][$name] = array('operator' => $operator, 'value' => $value, 'name' => $name); - } - } - - function setConstraints($array) { - - if (is_array($array)) { - - if ( ! isset($this->params['constraints']) ) { - $this->params['constraints'] = array(); - } - - foreach ($array as $constraint) { - $this->setConstraint($constraint['name'], $constraint['value'], $constraint['operator']); - } - } - } - - function setSiteId($siteId) { - - //used for urls - $this->query_params['siteId'] = $siteId; - $this->setConstraint('siteId', $siteId); - } - - function getSiteId() { - - if ( isset( $this->params['siteId'] ) ) { - - return $this->params['siteId']; - } - } - - function constraintsStringToArray($string) { - - if ($string) { - //print_r($string); - // add string to query params array for use in URLs. - $this->query_params['constraints'] = $string; - - return $this->parseConstraintsString($string); - } - } - - function parseConstraintsString($string) { - - $constraints = explode(',', $string); - $constraint_array = array(); - - foreach($constraints as $constraint) { - - foreach ($this->constraint_operators as $operator) { - - if (strpos($constraint, $operator)) { - - list ($name, $value) = explode($operator, $constraint); - $constraint_array[] = array('name' => $name, 'value' => html_entity_decode($value), 'operator' => $operator); - break; - } - } - } - - return $constraint_array; - } - - function getConstraints() { - - return $this->params['constraints']; - } - - function getConstraint( $key ) { - - if ( isset( $this->params['constraints'][$key] ) ) { - return $this->params['constraints'][$key]; - } - } - - function applyConstraints( $constraints = '', $db = '', $entity = '') { - - if ( !$db ) { - $db = $this->db; - } - - if ( ! $constraints ) { - $constraints = $this->getConstraints(); - } - //owa_coreAPI::debug(print_r($constraints, true)); - foreach ($constraints as $k => $constraint) { - - $this->applyConstraint($constraint, $db, $entity); - } - } - - function applyConstraint( $constraint, $db = '', $entity= '') { - - if ( ! $entity ) { - $entity = $this->baseEntity; - } - - if ( $this->isDimension( $constraint['name'] ) ) { - - $dim = $this->lookupDimension($constraint['name'], $entity); - - $col = $dim['column']; - $constraint['name'] = $col; - - $db->where($constraint['name'], $constraint['value'], $constraint['operator']); - } - - if ( $this->isMetric( $constraint['name'] ) ) { - - // get metric object - $m = $this->getMetricImplementation( $constraint['name'] ); - // if not calculated - if ( ! $m->isCalculated() ) { - $col = $m->getSelectWithNoAlias(); - $db->having($col, $constraint['value'], $constraint['operator']); - } else { - - $this->addError( 'Cannot add a calculated metric to a constraint.' ); - } - } - } - - function setSegment($segment) { - - $this->query_params['segment'] = $segment; - - if ( substr($segment, 0, 9) === 'dynamic::') { - - $segment = substr($segment, 9); - - } elseif ( substr($segment, 0, 4) === 'id::') { - // look up segment from db - } - - $parsed = $this->parseConstraintsString( $segment ); - $metrics = array(); - $dimensions = array(); - - foreach ( $parsed as $item ) { - - if ( $this->isMetric( $item['name'] ) ) { - $metrics[$item['name']] = $item; - - // add to all metrics or dimensions array - needed to determin base entity - /* + /** + * The params of the caller, either a report or graph + * + * @var array + */ + var $params = array(); + + /** + * The lables for calculated measures + * + * @var array + */ + var $labels = array(); + + /** + * Data Access Object + * + * @var object + */ + var $db; + + /** + * The dimensions to groupby + * + * @var array + */ + var $dimensions = array(); + + /** + * The Number of Dimensions to groupby + * + * @var integer + */ + var $dimensionCount; + + /** + * The table/column or denormalized dimensions + * associated with this metric + * + * @var array + */ + var $denormalizedDimensions = array(); + + var $_default_offset = 0; + var $page; + var $limit; + var $order; + var $format; + var $constraint_operators = array('==','!=','>=', '<=', '>', '<', '=~', '!~', '=@','!@'); + var $related_entities = array(); + var $related_dimensions = array(); + var $related_metrics = array(); + var $resultSet; + var $base_table; + var $metrics = array(); + var $metricsByTable = array(); + var $childMetrics = array(); + var $calculatedMetrics = array(); + var $query_params = array(); + var $baseEntity; + var $metricObjectsByEntityMap = array(); + var $metricObjectsCache = array(); + var $errors = array(); + var $formatters = array(); + var $segment; + + function __construct($db = '') { + + if ($db) { + $this->db = $db; + } else { + $this->db = owa_coreAPI::dbSingleton(); + } + + $this->formatters = array( + //'yyyymmdd' => array($this, 'dateFormatter'), + 'timestamp' => array($this, 'formatSeconds'), + 'percentage' => array($this, 'formatPercentage'), + 'integer' => array($this, 'numberFormatter'), + 'currency' => array($this, 'formatCurrency') + ); + + return parent::__construct(); + } + + + function setConstraint($name, $value, $operator = '') { + + if (empty($operator)) { + $operator = '='; + } + + if ( ! owa_lib::isEmpty( $value ) ) { + $this->params['constraints'][$name] = array('operator' => $operator, 'value' => $value, 'name' => $name); + } + } + + function setConstraints($array) { + + if (is_array($array)) { + + if ( ! isset($this->params['constraints']) ) { + $this->params['constraints'] = array(); + } + + foreach ($array as $constraint) { + $this->setConstraint($constraint['name'], $constraint['value'], $constraint['operator']); + } + } + } + + function setSiteId($siteId) { + + //used for urls + $this->query_params['siteId'] = $siteId; + $this->setConstraint('siteId', $siteId); + } + + function getSiteId() { + + if ( isset( $this->params['siteId'] ) ) { + + return $this->params['siteId']; + } + } + + function constraintsStringToArray($string) { + + if ($string) { + //print_r($string); + // add string to query params array for use in URLs. + $this->query_params['constraints'] = $string; + + return $this->parseConstraintsString($string); + } + } + + function parseConstraintsString($string) { + + $constraints = explode(',', $string); + $constraint_array = array(); + + foreach($constraints as $constraint) { + + foreach ($this->constraint_operators as $operator) { + + if (strpos($constraint, $operator)) { + + list ($name, $value) = explode($operator, $constraint); + $constraint_array[] = array('name' => $name, 'value' => html_entity_decode($value), 'operator' => $operator); + break; + } + } + } + + return $constraint_array; + } + + function getConstraints() { + + return $this->params['constraints']; + } + + function getConstraint( $key ) { + + if ( isset( $this->params['constraints'][$key] ) ) { + return $this->params['constraints'][$key]; + } + } + + function applyConstraints( $constraints = '', $db = '', $entity = '') { + + if ( !$db ) { + $db = $this->db; + } + + if ( ! $constraints ) { + $constraints = $this->getConstraints(); + } + //owa_coreAPI::debug(print_r($constraints, true)); + foreach ($constraints as $k => $constraint) { + + $this->applyConstraint($constraint, $db, $entity); + } + } + + function applyConstraint( $constraint, $db = '', $entity= '') { + + if ( ! $entity ) { + $entity = $this->baseEntity; + } + + if ( $this->isDimension( $constraint['name'] ) ) { + + $dim = $this->lookupDimension($constraint['name'], $entity); + + $col = $dim['column']; + $constraint['name'] = $col; + + $db->where($constraint['name'], $constraint['value'], $constraint['operator']); + } + + if ( $this->isMetric( $constraint['name'] ) ) { + + // get metric object + $m = $this->getMetricImplementation( $constraint['name'] ); + // if not calculated + if ( ! $m->isCalculated() ) { + $col = $m->getSelectWithNoAlias(); + $db->having($col, $constraint['value'], $constraint['operator']); + } else { + + $this->addError( 'Cannot add a calculated metric to a constraint.' ); + } + } + } + + function setSegment($segment) { + + $this->query_params['segment'] = $segment; + + if ( substr($segment, 0, 9) === 'dynamic::') { + + $segment = substr($segment, 9); + + } elseif ( substr($segment, 0, 4) === 'id::') { + // look up segment from db + } + + $parsed = $this->parseConstraintsString( $segment ); + $metrics = array(); + $dimensions = array(); + + foreach ( $parsed as $item ) { + + if ( $this->isMetric( $item['name'] ) ) { + $metrics[$item['name']] = $item; + + // add to all metrics or dimensions array - needed to determin base entity + /* if ( ! in_array($item['name'], $this->allMetrics) ) { - $this->allMetrics[] = $item['name']; - } - - if ( ! in_array($item['name'], $this->allDimensions) ) { - $this->allDimensions[] = $item['name']; - } + $this->allMetrics[] = $item['name']; + } + + if ( ! in_array($item['name'], $this->allDimensions) ) { + $this->allDimensions[] = $item['name']; + } */ - - } elseif ($this->isDimension( $item['name'] ) ) { - $dimensions[$item['name']] = $item; - } - } - - $this->segment = array('metrics' => $metrics, 'dimensions' => $dimensions); - } - - function getSegment() { - - return $this->segment; - } - - function getMetricNamesFromSegment() { - - if ( isset($this->segment['metrics'] ) ) { - - return array_keys($this->segment['metrics']); - } else { - - return array(); - } - } - - function getDimensionNamesFromSegment() { - - if ( isset( $this->segment['dimensions'] ) ) { - - return array_keys( $this->segment['dimensions'] ); - } else { - return array(); - } - } - - function chooseBaseEntity() { - - $metric_imps = array(); - - // load metric implementations - $all_metrics = $this->metrics; - - // add in metrics from segment if present - if ( isset($this->segment['metrics'] ) ) { - - //$all_metrics = array_unique( array_merge( $this->metrics, $this->getMetricNamesFromSegment() ) ); - } - - // add metrics from constraints - $all_metrics = array_unique( array_merge( $this->metrics, $this->getMetricNamesFromConstraints() ) ); - - // get all metric implmentations so we can see what entities we have to choose from - foreach ($all_metrics as $metric_name) { - - $metric_imps = array_merge($this->getMetricEntities($metric_name), $metric_imps); - } - - owa_coreAPI::debug('pre-reduce set of entities to choose from: '.print_r($metric_imps, true)); - - $entities = array(); - - // reduce metric entities. this will give us the fact tables to choose from. - foreach ($metric_imps as $mimp) { - - if (empty($entities)) { - $entities = $mimp; - } - - $entities = $this->reduceTables($mimp, $entities); - - if (empty($entities)) { - return $this->addError('illegal metric combination'); - } - } - - owa_coreAPI::debug('post-reduce set of entities to choose from: '.print_r($entities, true)); - - // check summary level of entities - $niceness = array(); - - foreach ($entities as $entity) { - - $niceness[$entity] = owa_coreAPI::entityFactory($entity)->getSummaryLevel(); - } - - // sort the fact table list by summary level - arsort($niceness); - - owa_coreAPI::debug('Entities summary levels: '.print_r($niceness, true)); - - $entity_count = count($niceness); - $i = 1; - //check entities for dimension relations - foreach ($niceness as $entity_name => $summary_level) { - - $error = false; - - // check dimensions in segment for relation to base entity. - if ( isset( $this->segment['dimensions'] ) ) { - - //$dims = array_unique( array_merge( $this->dimensions, $this->getDimensionNamesFromSegment() ) ); - $segment_dims = $this->getDimensionNamesFromSegment(); - - foreach ($segment_dims as $segment_dim) { - - $check = $this->isDimensionRelated($segment_dim, $entity_name); - - // is the realtionship check fails then move onto the next entity. - if (!$check) { - $error = true; - owa_coreAPI::debug("Segment dimension $dimension is not related to $entity_name. Moving on to next entity..."); - break; - } else { - // set related dimensions. this is needed for joins. - owa_coreAPI::debug("Segment Dimension: $segment_dim is related to $entity_name."); - } - } - } - - //cycle through each dimension from dim list and those found in constraints. - $dims = array_unique( array_merge( $this->dimensions, $this->getDimensionsFromConstraints() ) ); - - owa_coreAPI::debug(sprintf('Dimensions: %s',print_r($this->dimensions, true))); - - owa_coreAPI::debug(sprintf('Checking the following dimensions for relation to %s: %s',$entity_name, print_r($dims, true))); - - foreach ($dims as $dimension) { - - $check = $this->isDimensionRelated($dimension, $entity_name); - - // is the realtionship check fails then move onto the next entity. - if (!$check) { - $error = true; - owa_coreAPI::debug("$dimension is not related to $entity_name. Moving on to next entity..."); - break; - } else { - // set related dimensions. this is needed for joins. - $dim_array = $this->getDimensionByEntityName($dimension, $entity_name); - - $this->setRelatedDimension( $dim_array ); - owa_coreAPI::debug("Dimension: $dimension is related to $entity_name."); - } - } - - // is no error then everythig is related and we are good to go. - if (!$error) { - owa_coreAPI::debug('optimal base entity is: '.$entity_name); - $this->baseEntity = owa_coreAPI::entityFactory($entity_name); - return $this->baseEntity; - } - - if ($i === $entity_count) { - $this->addError('illegal dimension combination: '.$dimension); - } else { - $i++; - } - } - } - - function setRelatedDimension($dimension) { - - $this->related_dimensions[$dimension['name']] = $dimension; - } - - function getDimensionsFromConstraints() { - - $dims = array(); - - $constraints = $this->getConstraints(); - //print_r($constraints); - if (!empty($constraints)) { - - foreach ($constraints as $carray) { - - if ($this->isDimension( $carray['name'] ) ) { - $dims[] = $carray['name']; - } - } - } - - return $dims; - } - - function getMetricNamesFromConstraints() { - - $metrics = array(); - foreach ($this->getConstraints() as $k => $constraint) { - - if ( $this->isMetric( $constraint['name'] ) ) { - $metrics[] = $constraint['name']; - } - } - - return $metrics; - } - - function isDimensionRelated($dimension_name, $entity_name) { - - $entity = owa_coreAPI::entityFactory($entity_name); - - $dimension = $this->lookupDimension($dimension_name, $entity); - - if ($dimension['denormalized'] === true) { - //$this->related_dimensions[$dimension['name']] = $dimension; - owa_coreAPI::debug("Dimension: $dimension_name is denormalized into $entity_name"); - return true; - } else { - - $fk = $this->getDimensionForeignKey($dimension, $entity); - - if ($fk) { - owa_coreAPI::debug("Dimension: $dimension_name is related to $entity_name"); - //$this->related_dimensions[$dimension['name']] = $dimension; - return true; - } else { - owa_coreAPI::debug("Could not find a foreign key for $dimension_name in $entity_name"); - } - } - } - - function getMetricEntities($metric_name) { - owa_coreAPI::debug("getting metric entities for $metric_name"); - - //get the class implementations - $s = owa_coreAPI::serviceSingleton(); - $classes = $s->getMetricClasses($metric_name); - - $entities = array(); - - // cycles through metric classes and get their entity names - foreach ($classes as $name => $map) { - $m = owa_coreAPI::metricFactory($map['class'], $map['params']); - - // check to see if this is a calculated metric - if ($m->isCalculated()) { - - foreach ($m->getChildMetrics() as $cmetric_name) { - $this->addCalculatedMetric($m); - $entities = array_merge($this->getMetricEntities($cmetric_name), $entities); - } - - } else { - $this->metricObjectsByEntityMap[$m->getEntityName()][$metric_name] = $m; - $entities[$metric_name][] = $m->getEntityName(); - } - - } - - return $entities; - } - - function reduceTables($new, $old) { - - return array_intersect($new, $old); - } - - function getDimensionForeignKey($dimension, $entity) { - - if ($dimension) { - //$entity = ; - $dim = $dimension; - $fk = array(); - // check for foreign key column by name if dimension specifies one - //print_r($dim); - if ( isset($dim['foreign_key_name']) && ! empty($dim['foreign_key_name'])) { - // get foreign key col by - if ($entity->isForeignKeyColumn($dim['foreign_key_name'])){ - $fk = array('col' => $dim['foreign_key_name'], 'entity' => $entity); - } - - } else { - // if not check for foreign key by entity name - //check to see if the metric's entity has a foreign key to the dimenesion table. - $fk = array(); - - $fkcol = $entity->getForeignKeyColumn($dim['entity']); - owa_coreAPI::debug("Foreign Key check: ". print_r($fkcol, true)); - if ($fkcol) { - $fk['col'] = $fkcol; - $fk['entity'] = $entity; - } - } - - return $fk; - } - } - - function isDimension( $name ) { - - $dims = owa_coreAPI::getAllDimensions(); - //print_r($dims); - return in_array( $name, array_keys( $dims ) ); - } - - function isMetric( $name ) { - - $metrics = owa_coreAPI::getAllMetrics(); - return in_array( $name, array_keys( $metrics ) ); - } - - function getDimensionByEntityName($dim_name, $entity_name) { - - $entity = owa_coreAPI::entityFactory($entity_name); - return $this->lookupDimension($dim_name, $entity); - } - - /** - * Retrieves dimension given a name and associated fact table entity. - * - * @param $name string the name of the dimenson - * @param $entity object the entity object - * @return array - */ - function lookupDimension($name, $entity) { - - // check for denormalized - $service = owa_coreAPI::serviceSingleton(); - $dim = $service->getDenormalizedDimension($name, $entity->getName()); - - if ($dim) { - //apply table aliasing to dimension column - $dim['column'] = $entity->getTableAlias().'.'.$dim['column']; - } else { - - // check for normalized dim - if (array_key_exists($name, $this->related_dimensions)) { - $dim = $this->related_dimensions[$name]; - } else { - - $dim = $service->getDimension($name); - - if ($dim) { - $dimEntity = owa_coreAPI::entityFactory($dim['entity']); - // alias needs to use fk name in case there are two joins on the - // same table. This is also used in addRelation method - $alias = $dimEntity->getTableAlias().'_via_'.$dim['foreign_key_name']; - //$dim['column'] = $dimEntity->getTableAlias().'.'.$dim['column']; - $dim['column'] = $alias.'.'.$dim['column']; - } else { - $msg = "$name is not a registered dimension."; - owa_coreAPI::debug($msg); - $this->addError($msg); - } - - } - } - - return $dim; - } - - function setLimit($value) { - - if (!empty($value)) { - - $this->limit = $value; - } - } - - function setOrder($value) { - - if (!empty($value)) { - $this->params['order'] = $value; - } - } - - function getOrder() { - - if (array_key_exists('order', $this->params)) { - return $this->params['order']; - } - } - - function setSort($column, $order) { - - //$this->params['orderby'][] = array($this->getColumnName($column), $order); - } - - function setSorts($array) { - - if (is_array($array)) { - - if (!empty($this->params['orderby'])) { - $this->params['orderby'] = array_merge($array, $this->params['orderby']); - - } else { - $this->params['orderby'] = $array; - } - } - } - - function applySorts() { - - $sorts = $this->params['orderby']; - - if ($sorts) { - - foreach ($sorts as $sort) { - - $sort_col = $sort[0]; - - if ( $this->isMetric( $sort[0] ) ) { - $sort_metric = $this->getMetricImplementation($sort[0]); - if ( $sort_metric->isCalculated() ) { - - $child_metrics = $sort_metric->getChildMetrics(); - $formula = $sort_metric->getFormula(); - - // replace metric names with unique identifiers - // so that follow on replacement doesn't clobber anything. - foreach ($child_metrics as $child) { - - $formula = str_replace($child, '__'.$child, $formula); - } - - // now replace the names with seldct statements. - foreach ($child_metrics as $child) { - $child_metric = $this->getMetricImplementation( $child ); - $select = $child_metric->getSelect(); - $formula = str_replace('__'.$child, $select[0], $formula); - } - - $sort_col = $formula; - } - } - - $this->db->orderBy($sort_col, $sort[1]); - } - } - } - - function sortStringToArray($string) { - - if ($string) { - - // add string to query params array for use in URLs. - $this->query_params['sort'] = $string; - - $sorts = explode(',', $string); - - $sort_array = array(); - - foreach ($sorts as $sort) { - - if (strpos($sort, '-')) { - $column = substr($sort, 0, -1); - $order = 'DESC'; - } else { - $column = $sort; - $order = 'ASC'; - } - - //$col_name = $this->getColumnName($column); - $check = $this->isSortValid($column); - - if ($check) { - - $col_name = $column; - - if ($col_name) { - $sort_array[$sort][0] = $col_name; - $sort_array[$sort][1] = $order; - - } else { - $this->addError("$column is not a valid column to sort on"); - } - } - } - - return $sort_array; - } - } - - function isSortValid($needle) { - - $haystack = array_merge($this->metrics, $this->dimensions); - return in_array($needle, $haystack); - } - - function setPage($value) { - - if (!empty($value)) { - - $this->page = $value; - - if (!empty($this->pagination)) { - $this->pagination->setPage($value); - } - } - } - - function setOffset($value) { - - if (!empty($value)) { - $this->params['offset'] = $value; - } - } - - function setFormat($value) { - if (!empty($value)) { - $this->format; - $this->params['result_format'] = $value; - } - } - - function setPeriod($value) { - if (!empty($value)) { - $this->params['period'] = $value; - } - } - - function setTimePeriod($period_name = '', $startDate = null, $endDate = null, $startTime = null, $endTime = null) { - - $map = false; - - if ($startDate && $endDate) { - $period_name = 'date_range'; - $map = array('startDate' => $startDate, 'endDate' => $endDate); - $dimension_name = 'date'; - $format = 'yyyymmdd'; - } elseif ($startTime && $endTime) { - $period_name = 'time_range'; - $map = array('startTime' => $startTime, 'endTime' => $endTime); - $dimension_name = 'timestamp'; - $format = 'timestamp'; - } else { - owa_coreAPI::debug('no start/end params passed to owa_metric::setTimePeriod'); - $dimension_name = 'date'; - $format = 'yyyymmdd'; - } - - // add to query params array for use in URL construction - if ($map) { - $this->query_params = array_merge($map, $this->query_params); - } else { - $this->query_params['period'] = $period_name; - } - - $p = owa_coreAPI::supportClassFactory('base', 'timePeriod'); - - $p->set($period_name, $map); - - $this->setPeriod($p); - - $start = $p->startDate->get($format); - $end = $p->endDate->get($format); - - $this->setConstraint($dimension_name, array('start' => $start, 'end' => $end), 'BETWEEN'); - - - } - - function setStartDate($date) { - - if (!empty($date)) { - $this->params['startDate'] = $date; - } - } - - function setEndDate($date) { - if (!empty($date)) { - $this->params['endDate'] = $date; - } - } - - function applyMetaDataToResults($results) { - - $new_rows = array(); - - foreach ($results as $row) { - - $new_rows[] = $this->applyMetaDataToSingleResultRow($row); - } - - return $new_rows; - } - - function applyMetaDataToSingleResultRow($row) { - - $new_row = array(); - - foreach ($row as $k => $v) { - - if (in_array($k, $this->dimensions)) { - $type = 'dimension'; - $dim = $this->lookupDimension($k, $this->baseEntity); - $data_type = $dim['data_type']; - } elseif (in_array($k, $this->metrics)){ - $type = 'metric'; - $data_type = $this->getMetric($k)->getDataType(); - } - else { - // can't throw exception here as the metrics are sometimes used to geenrate calculated metrics - // therefor no meta data is applied as this stage. - //throw new Exception($k.' is not a metric or dimension. Check the configuration!'); - } - - - - $new_row[$k] = array( - 'result_type' => $type, - 'name' => $k, - 'value' => $v, - 'formatted_value' => $this->formatValue($data_type, $v), - 'label' => $this->getLabel($k), 'data_type' => $data_type); - } - - return $new_row; - } - - function formatValue($type, $value) { - - if (array_key_exists($type, $this->formatters)) { - - $formatter = $this->formatters[$type]; - - } else { - $s = owa_coreAPI::serviceSingleton(); - $formatter = $s->getFormatter($type); - } - - // If we found a formatter, use it - if (!empty($formatter)) { - - $value = call_user_func($formatter, $value); - } - - return $value; - } - - function numberFormatter($value) { - - return number_format($value); - } - - function formatSeconds($value) { - - return date("G:i:s",mktime(0,0,($value))); - } - - function formatPercentage($value) { - - return number_format($value * 100, 2).'%'; - } - - function formatCurrency($value) { - - return owa_lib::formatCurrency( - $value, - owa_coreAPI::getSetting( 'base', 'currencyLocal' ), - owa_coreAPI::getSetting( 'base', 'currencyISO3' ) - ); - } - - /** - * Sets an individual label - * return the key so that it can be nested - * @return $key string - */ - function addLabel($key, $label) { - - $this->labels[$key] = $label; - return $key; - } - - function getLabel($key = '') { - - if (array_key_exists($key, $this->labels)) { - return $this->labels[$key]; - } else { - //owa_coreAPI::debug("No label found for $key."); - } - - } - - /** - * Retrieve the labels of the measures - * - */ - function getLabels() { - - return $this->labels; - } - - /** - * Sets an individual label - * return the key so that it can be nested - * @return $key string - */ - function setLabel($label) { - - $this->labels[$this->getName()] = $label; - } - - /** - * Set the labels of the measures - * - */ - function setLabels($array) { - - $this->labels = $array; - } - - function getPeriod() { - - return $this->params['period']; - } - - function getLimit() { - - return $this->limit; - } - - /** - * Adds a dimension to the dimension map - * - * Retrieves dimension info from service layer and checks to see if - * dimension is denromalized or if it is a valid relation - */ - function setDimension($name) { - - if ($name) { - $this->dimensions[] = $name; - } - } - - function setDimensions($array) { - - if ($array) { - - foreach($array as $name) { - - $this->setDimension($name); - } - } - } - - function dimensionsStringToArray($string) { - - // add string to query params array for use in URLs. - $this->query_params['dimensions'] = $string; - return explode(',', $string); - } - - function metricsStringToArray($string) { - - // add string to query params array for use in URLs. - $this->query_params['metrics'] = $string; - return explode(',', $string); - } - - - function dimensionsArrayToString($array) { - - return implode(',', $array); - } - - /** - * Applies dimensional sql to dao object - */ - function applyDimensions() { - - foreach ($this->dimensions as $dimension_name) { - $dim = $this->lookupDimension($dimension_name, $this->baseEntity); - // add column name to select statement - $this->db->selectColumn($dim['column'], $dim['name']); - // add groupby - $this->db->groupBy($dim['column']); - $this->addLabel($dim['name'], $dim['label']); - } - } - - function applyJoins() { - - foreach($this->related_dimensions as $dim) { - $this->addRelation($dim); - } - } - - function getBaseEntity() { - return $this->baseEntity; - } - - function addRelation($dim, $db = '', $entity = '') { - - if ( ! $db ) { - - $db = $this->db; - } - - if ( ! $entity ) { - $entity = $this->getBaseEntity(); - } - - // if denomalized, skip - if ($dim['denormalized'] === true) { - return; - } - - // have already determined base enttiy at this point so use that. - $fk = $this->getDimensionForeignKey($dim, $entity); - //print_r($fk); - //print $fk; - if ($fk) { - - // create dimension entity - $dimEntity = owa_coreAPI::entityFactory($dim['entity']); - // get foreign key column - //$bm = $this->getBaseMetric(); - //$fpk_col = $bm->entity->getProperty($fk); - $fpk_col = $fk['entity']->getProperty($fk['col']); - //$fpk_col = $this->baseEntity->getProperty($fk['col']); - - //print_r($fk['col']); - $fpk = $fpk_col->getForeignKey(); - // add join - //print_r($fpk); - // needed to make joins unique in cases where there are - // two joins onthe same table using different foreign keys. - $alias = $dimEntity->getTableAlias().'_via_'.$dim['foreign_key_name']; - //$this->db->join(OWA_SQL_JOIN, $dimEntity->getTableName(), $dimEntity->getTableAlias(), $fk['entity']->getTableAlias().'.'.$fk['col'], $dimEntity->getTableAlias().'.'.$fpk[1]); - $db->join(OWA_SQL_JOIN, $dimEntity->getTableName(), $alias, $fk['entity']->getTableAlias().'.'.$fk['col'], $alias.'.'.$fpk[1]); - - //$this->addColumn($dim['name'], $dimEntity->getTableAlias().'.'.$dim['column']); - $this->addColumn($dim['name'], $alias.'.'.$dim['column']); - - } else { - // add error result set - owa_coreAPI::debug(sprintf('%s metric does not have relation to dimension %s', $fk['entity']->getName(), $dim['name'])); - } - - } - - // remove - function addMetric($metric_name, $child = false) { - - $ret = false; - - $m = $this->getMetric($metric_name); - - if (!$m) { - $m = owa_coreAPI::metricFactory($metric_name); - - if ($m) { - - - // necessary if the metric was first added as a child but later added as a parent. - if (!$child) { - - if (array_key_exists($metric_name, $this->childMetrics)) { - unset ($this->childMetrics[$metric_name]); - } - } else { - // add child metrics to child metric maps - // check to see if it wasn't already added as a non-child metric. - if (!array_key_exists($metric_name, $this->metrics)){ - $this->childMetrics[$metric_name] = $metric_name; - } - } - - // check to see if this is a calculated metric - if ($m->isCalculated()) { - - return $this->addCalculatedMetric($m); - } - - if ($this->checkForFactTableRelation($m)) { - - $this->metrics[$metric_name] = $m; - $this->metricsByTable[$m->getTableName()] = $metric_name; - $this->addSelect($m->getSelect()); - $this->addLabel($m->getName(), $m->getLabel()); - - $ret = true; - } - - } else { - $this->addError("$metric_name is not a metric."); - } - } else { - $ret = true; - } - - - - return $ret; - } - - function addCalculatedMetric($calc_metric_obj) { - - // add label of calculated metric obj - $this->addLabel($calc_metric_obj->getName(),$calc_metric_obj->getLabel()); - // add to calculated metric map - $this->calculatedMetrics[$calc_metric_obj->getName()] = $calc_metric_obj; - - } - - function getCalculatedMetricByName($name) { - - return $this->calculatedMetrics[$name]; - } - - function addSelect($select_array) { - - $this->params['selects'][] = $select_array; - } - - //depricated? - function getSelects() { - - if (array_key_exists('selects', $this->params)) { - return $this->params['selects']; - } - } - - // can only be called after base entity is determined. - function getMetricImplementation($metric_name) { - - if (!array_key_exists($metric_name, $this->calculatedMetrics)) { - - return $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$metric_name]; - - } else { - return $this->getCalculatedMetricByName($metric_name); - } - } - - function applySelects() { - //print_r($this->metrics); - foreach($this->metrics as $k => $metric_name) { - - if (!array_key_exists($metric_name, $this->calculatedMetrics)) { - - $m = $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$metric_name]; - - $select = $m->getSelect(); - //print_r ($select); - $this->db->selectColumn($select[0], $select[1]); - } else { - $m = $this->getCalculatedMetricByName($metric_name); - } - - $this->addLabel($m->getName(), $m->getLabel()); - } - - // add selects for calculated metrics - if (!empty($this->calculatedMetrics)) { - - // loop through calculated metric objects - foreach ($this->calculatedMetrics as $cmetric) { - //create child metrics - foreach( $cmetric->getChildMetrics() as $child_name) { - // check to see if the metric has already been added - if (!in_array($child_name, $this->metrics)) { - - $child = $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$child_name]; - $select = $child->getSelect(); - //print_r ($select[0]); - $this->db->selectColumn($select[0], $select[1]); - // needed so we can remove this temp metric later - $this->childMetrics[] = $child_name; - owa_coreAPI::debug("Added $child_name to ChildMetrics array"); - } - } - } - } - } - - function getFormat() { - - if (array_key_exists('result_format', $this->params)) { - return $this->params['result_format']; - } - } - - function getColumnName($string) { - - //$string = trim($string); - if (array_key_exists($string, $this->related_dimensions)) { - return $this->related_dimensions[$string]['column']; - } - - if (array_key_exists($string, $this->related_metrics)) { - return $string; - } - - - //return $string; - - } - - /** - * Sets a metric's column name into the all_columns map - * - * this is needed when combining metrics so that sort and - * constraint column names can be looked up fro ma single map. - * - * NEEDED??? - */ - function addColumn($name, $col) { - - $this->all_columns[$name] = $col; - } - - function addError($msg) { - - $this->errors[] = $msg; - owa_coreAPI::debug($msg); - } - - /** - * Generates a result set for the metric - * - */ - function getResults() { - - // get paginated result set object - $rs = owa_coreAPI::supportClassFactory('base', 'paginatedResultSet'); - - $bm = $this->chooseBaseEntity(); - - if ($bm) { - - $bname = $bm->getName(); - - owa_coreAPI::debug("Using $bname as base entity for making result set."); - - // set constraints - $this->applyJoins(); - owa_coreAPI::debug('about to apply constraints'); - $this->applyConstraints(); - owa_coreAPI::debug('about to apply selects'); - $this->applySelects(); - - // set from table - if ( $this->segment ) { - $this->db->selectFrom( $this->generateSegmentQuery( $bm ), $bm->getTableAlias() ); - } else { - $this->db->selectFrom($bm->getTableName(), $bm->getTableAlias()); - } - - // generate aggregate results - $results = $this->db->getOneRow(); - // merge into result set - if ($results) { - $rs->aggregates = array_merge($this->applyMetaDataToSingleResultRow($results), $rs->aggregates); - } - - // setup dimensional query - if (!empty($this->dimensions)) { - - $this->applyJoins(); - // apply dimensional SQL - $this->applyDimensions(); - - $this->applySelects(); - - // set from table - if ( $this->segment ) { - $this->db->selectFrom( $this->generateSegmentQuery( $bm ), $bm->getTableAlias() ); - } else { - $this->db->selectFrom($bm->getTableName(), $bm->getTableAlias()); - } - - // pass limit to db object if one exists - if (!empty($this->limit)) { - $rs->setLimit($this->limit); - } - // pass limit to db object if one exists - if (!empty($this->page)) { - $rs->setPage($this->page); - } - - $this->applyConstraints(); - - if (array_key_exists('orderby', $this->params)) { - $sorts = $this->params['orderby']; - // apply sort by - if ($sorts) { - $this->applySorts(); - foreach ($sorts as $sort) { - //$this->db->orderBy($sort[0], $sort[1]); - $rs->sortColumn = $sort[0]; - if (isset($sort[1])){ - $rs->sortOrder = strtolower($sort[1]); - } else { - $rs->sortOrder = 'asc'; - } - } - } - } - - // add labels - $rs->setLabels($this->getLabels()); - - // generate dimensonal results - $results = $rs->generate($this->db); - - $rs->resultsRows = $this->applyMetaDataToResults($results); - } - - // add labels - $rs->setLabels($this->getLabels()); - - // add period info - - $rs->setPeriodInfo($this->params['period']->getAllInfo()); - - $rs = $this->computeCalculatedMetrics($rs); - - // add urls - $urls = $this->makeResultSetUrls(); - $rs->self = $urls['self']; - - if ($rs->more) { - - $rs->next = $urls['next']; - } - - if ($this->page >=2) { - $rs->previous = $urls['previous']; - } - - $rs->createResultSetHash(); - } - - $rs->errors = $this->errors; - - $rs->setRelatedDimensions( $this->getAllRelatedDimensions( $bm ) ); - $rs->setRelatedMetrics( $this->getAllRelatedMetrics( $bm ) ); - - return $rs; - } - - function generateSegmentQuery( $base_entity ) { - - $segment = $this->getSegment(); - $segment_entity = owa_coreAPI::entityFactory($base_entity->getName()); - $segment_entity->setTableAlias( $segment_entity->getTableAlias() . '_segment'); - - if ( $segment ) { - // use a new data access object - $db = owa_coreAPI::dbFactory(); - $db->select( $segment_entity->getTableAlias().'.*' ); - $db->from( $segment_entity->getTableName(), $segment_entity->getTableAlias() ); - - if ( isset( $segment['metrics'] ) ) { - - //$this->applyConstraints( $segment['metrics'], $db); - } - - if ( isset( $segment['dimensions'] ) ) { - //print_r($segment); - foreach ($segment['dimensions'] as $k => $dim) { - - $check = $this->isDimensionRelated($dim['name'], $segment_entity->getName() ); - if ( $check ) { - $dimension = $this->lookupDimension($dim['name'], $segment_entity); - - if ( ! isset($dimension['denormalized'] ) || $dimension['denormalized'] != true ) { - $this->addRelation($dimension, $db, $segment_entity); - } - } - } - //print_r( $segment['dimensions'] ); - $this->applyConstraints( $segment['dimensions'], $db, $segment_entity); - - // apply siteId, startDate, and endDate constraints - $constraint_names = array('siteId', 'date'); - $constraints_apply = array(); - //print_r($this->params['constraints']); - foreach ( $constraint_names as $name ) { - - $con = $this->getConstraint( $name ); - if ( $con ) { - $constraints_apply[$name] = $con; - } - } - - if ( $constraints_apply ) { - $this->applyConstraints( $constraints_apply, $db, $segment_entity); - } - } - - return sprintf('(%s)', $db->generateSelectQuerySql() ); - } - - } - - function computeCalculatedMetrics($rs) { - - foreach ($this->calculatedMetrics as $cm) { - - // add aggregate metric - $formula = $cm->getFormula(); - $div_by_zero = false; - - //owa_coreAPI::debug( "checking calculated metrics..." ); - //owa_coreAPI::debug( $rs->aggregates ); - foreach ($cm->getChildMetrics() as $metric_name) { - - $ag_value = $rs->getAggregateMetric($metric_name); - - if (empty($ag_value) || $ag_value == 0) { - $ag_value = 0; - $div_by_zero = true; - } - - $formula = str_replace($metric_name, $ag_value, $formula); - } - - if ( ! $div_by_zero ) { - $value = $this->evalFormula($formula); - } else { - $value = 0; - } - - $rs->setAggregateMetric($cm->getName(), $value, $cm->getLabel(), $cm->getDataType(), $this->formatValue($cm->getDataType(), $value)); - - // add dimensional metric - - if ($rs->getRowCount() > 0) { - - foreach ($rs->resultsRows as $k => $row) { - - // add aggregate metric - $formula = $cm->getFormula(); - $row_div_by_zero = false; - foreach ($cm->getChildMetrics() as $metric_name) { - - if (array_key_exists($metric_name, $row)) { - $row_value = $row[$metric_name]['value']; - } else { - $row_value = ''; - } - if (empty($row_value) || $row_value == 0) { - $row_value = 0; - $row_div_by_zero = true; - } - - $formula = str_replace($metric_name, $row_value, $formula); - - } - - if ( ! $row_div_by_zero ) { - $value = $this->evalFormula($formula); - } else { - $value = 0; - } - - $rs->appendRow($k, 'metric', $cm->getName(), $value, $cm->getLabel(), $cm->getDataType(), $this->formatValue($cm->getDataType(), $value)); - } - } - } - - // clean up by removing child metrics before returning the result set. - foreach ($this->childMetrics as $metric_name) { - - $rs->removeMetric($metric_name); - } - - return $rs; - } - - function evalFormula($formula) { - - //safety first. should only be computing numbers. - $formula = str_replace('$','', $formula); - - // need parens and @ to handle divsion by zero errors - $formula = '$value = ('.$formula.');'; - //print $formula; - // calc - @ eval($formula); - - if (!$value) { - $value = 0; - } - - return $value; - } - - /** - * Return the approraite metric implementation for the baseEntity - * Must be called after the base entity has been determined - * - * @param string $name the name of the metric - * - */ - function getMetric($name) { - - // check to see if the entity object map is loaded - if ( ! in_array( $name, $this->metrics ) ) { - // if not load it forthat metric - $this->getMetricEntities($name); - } - - return $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$name]; - - } - - - - function setQueryStringParam($name, $string) { - - $this->query_params[$name] = $string; - } - - function makeResultSetUrls() { - - $urls = array(); - // get api url - $api_url = owa_coreAPI::getSetting('base', 'api_url'); - // get base query params - $query_params = $this->query_params; - // add api command - $query_params['do'] = 'getResultSet'; - //add format - if ($this->format) { - $query_params['format'] = $this->format; - } else { - $query_params['format'] = 'json'; - } - // add current page if any - if ($this->page) { - $query_params['page'] = $this->page; - } - // add limit - if ($this->limit) { - $query_params['resultsPerPage'] = $this->limit; - } - - // build url for this result set - $link_template = owa_coreAPI::getSetting('base', 'link_template'); - $q = $this->buildQueryString($query_params); - $urls['self'] = sprintf($link_template, $api_url, $q); - - // build url for next page of result set - $next_query_params = $query_params; - if ($this->page) { - $next_query_params['page'] = $query_params['page'] + 1; - } else { - $next_query_params['page'] = 2; - } - - $nq = $this->buildQueryString($next_query_params); - $urls['next'] = sprintf($link_template, $api_url, $nq); - - // build previous url if page is greater than 2 - if ($this->page >= 2) { - $previous_query_params = $query_params; - $previous_query_params['page'] = $query_params['page'] - 1; - $pq = $this->buildQueryString($previous_query_params); - $urls['previous'] = sprintf($link_template, $api_url, $pq); - } - - $base_query_params = $this->query_params; - $base_query_params['format'] = $this->format; - - // build pagination url template for use in constructing - $q = $this->buildQueryString($base_query_params); - $url['base_url'] = sprintf($link_template, $api_url, $q); - - return $urls; - } - - function buildQueryString($params, $seperator = '&') { - - $new = array(); - //get namespace - $ns = owa_coreAPI::getSetting('base', 'ns'); - foreach ($params as $k => $v) { - - $new[$ns.$k] = $v; - } - - return http_build_query($new,'', $seperator); - } - - function getAllRelatedDimensions($entity) { - - $s = owa_coreAPI::serviceSingleton(); - $dims = array(); - $denormalized_dims = $s->denormalizedDimensions; - - foreach ( $denormalized_dims as $ddim_imp) { - - foreach ( $ddim_imp as $k => $ddim) { - - if ($k === $entity->getName()) { - $dims[ $ddim['family'] ][] = array( 'name' => $ddim['name'], 'label' => $ddim['label'] ); - } - } - } - - $normalized_dims = $s->dimensions; - - foreach ( $normalized_dims as $k => $ndim ) { - - // check to see if realation exists with dim's speficied foreign key - $fk = $ndim['foreign_key_name']; - if ( $fk ) { - - $col_exists = $entity->getProperty($fk); - - } else { - // check to see if there is any foreign key to the dim's entity - $col_exists = $entity->getForeignKeyColumn( $ndim['entity'] ); - } - - if ( $col_exists ) { - $dims[ $ndim['family'] ][] = array( 'name' => $ndim['name'], 'label' => $ndim['label'] ); - } - } - - return $dims; - } - - function getAllRelatedMetrics( $entity ) { - - $related_metrics = array(); - $s = owa_coreAPI::serviceSingleton(); - $all_metrics = $s->getAllMetrics(); - $entity_name = $entity->getName(); - $s = owa_coreAPI::serviceSingleton(); - $metricsByEntity = $s->getMap('metricsByEntity'); - foreach ($all_metrics as $metric_name => $implementations) { - - foreach ($implementations as $implementation) { - - $m = owa_coreAPI::metricFactory( $implementation['class'], $implementation['params'] ); - - if ( $m->isCalculated() ) { - - $children = $m->getChildMetrics(); - $error = false; - foreach( $children as $child ) { - - if ( ! isset($metricsByEntity[$entity_name][$child])) { - - $error = true; - } - } - - if ( ! $error ) { - - $related_metrics[$implementation['group']][] = array( - 'name' => $metric_name, - 'label' => $implementation['label'], - 'description' => $implementation['description'], - 'group' => $implementation['group'] - ); - - continue; - } - - - } else { - - if ( $entity_name === $m->getEntityName() ) { - - $related_metrics[$implementation['group']][] = array( - 'name' => $metric_name, - 'label' => $implementation['label'], - 'description' => $implementation['description'], - 'group' => $implementation['group'] - ); - - continue; - } - } - } - } - - return $related_metrics; - } + + } elseif ($this->isDimension( $item['name'] ) ) { + $dimensions[$item['name']] = $item; + } + } + + $this->segment = array('metrics' => $metrics, 'dimensions' => $dimensions); + } + + function getSegment() { + + return $this->segment; + } + + function getMetricNamesFromSegment() { + + if ( isset($this->segment['metrics'] ) ) { + + return array_keys($this->segment['metrics']); + } else { + + return array(); + } + } + + function getDimensionNamesFromSegment() { + + if ( isset( $this->segment['dimensions'] ) ) { + + return array_keys( $this->segment['dimensions'] ); + } else { + return array(); + } + } + + function chooseBaseEntity() { + + $metric_imps = array(); + + // load metric implementations + $all_metrics = $this->metrics; + + // add in metrics from segment if present + if ( isset($this->segment['metrics'] ) ) { + + //$all_metrics = array_unique( array_merge( $this->metrics, $this->getMetricNamesFromSegment() ) ); + } + + // add metrics from constraints + $all_metrics = array_unique( array_merge( $this->metrics, $this->getMetricNamesFromConstraints() ) ); + + // get all metric implmentations so we can see what entities we have to choose from + foreach ($all_metrics as $metric_name) { + + $metric_imps = array_merge($this->getMetricEntities($metric_name), $metric_imps); + } + + owa_coreAPI::debug('pre-reduce set of entities to choose from: '.print_r($metric_imps, true)); + + $entities = array(); + + // reduce metric entities. this will give us the fact tables to choose from. + foreach ($metric_imps as $mimp) { + + if (empty($entities)) { + $entities = $mimp; + } + + $entities = $this->reduceTables($mimp, $entities); + + if (empty($entities)) { + return $this->addError('illegal metric combination'); + } + } + + owa_coreAPI::debug('post-reduce set of entities to choose from: '.print_r($entities, true)); + + // check summary level of entities + $niceness = array(); + + foreach ($entities as $entity) { + + $niceness[$entity] = owa_coreAPI::entityFactory($entity)->getSummaryLevel(); + } + + // sort the fact table list by summary level + arsort($niceness); + + owa_coreAPI::debug('Entities summary levels: '.print_r($niceness, true)); + + $entity_count = count($niceness); + $i = 1; + //check entities for dimension relations + foreach ($niceness as $entity_name => $summary_level) { + + $error = false; + + // check dimensions in segment for relation to base entity. + if ( isset( $this->segment['dimensions'] ) ) { + + //$dims = array_unique( array_merge( $this->dimensions, $this->getDimensionNamesFromSegment() ) ); + $segment_dims = $this->getDimensionNamesFromSegment(); + + foreach ($segment_dims as $segment_dim) { + + $check = $this->isDimensionRelated($segment_dim, $entity_name); + + // is the realtionship check fails then move onto the next entity. + if (!$check) { + $error = true; + owa_coreAPI::debug("Segment dimension $dimension is not related to $entity_name. Moving on to next entity..."); + break; + } else { + // set related dimensions. this is needed for joins. + owa_coreAPI::debug("Segment Dimension: $segment_dim is related to $entity_name."); + } + } + } + + //cycle through each dimension from dim list and those found in constraints. + $dims = array_unique( array_merge( $this->dimensions, $this->getDimensionsFromConstraints() ) ); + + owa_coreAPI::debug(sprintf('Dimensions: %s',print_r($this->dimensions, true))); + + owa_coreAPI::debug(sprintf('Checking the following dimensions for relation to %s: %s',$entity_name, print_r($dims, true))); + + foreach ($dims as $dimension) { + + $check = $this->isDimensionRelated($dimension, $entity_name); + + // is the realtionship check fails then move onto the next entity. + if (!$check) { + $error = true; + owa_coreAPI::debug("$dimension is not related to $entity_name. Moving on to next entity..."); + break; + } else { + // set related dimensions. this is needed for joins. + $dim_array = $this->getDimensionByEntityName($dimension, $entity_name); + + $this->setRelatedDimension( $dim_array ); + owa_coreAPI::debug("Dimension: $dimension is related to $entity_name."); + } + } + + // is no error then everythig is related and we are good to go. + if (!$error) { + owa_coreAPI::debug('optimal base entity is: '.$entity_name); + $this->baseEntity = owa_coreAPI::entityFactory($entity_name); + return $this->baseEntity; + } + + if ($i === $entity_count) { + $this->addError('illegal dimension combination: '.$dimension); + } else { + $i++; + } + } + } + + function setRelatedDimension($dimension) { + + $this->related_dimensions[$dimension['name']] = $dimension; + } + + function getDimensionsFromConstraints() { + + $dims = array(); + + $constraints = $this->getConstraints(); + //print_r($constraints); + if (!empty($constraints)) { + + foreach ($constraints as $carray) { + + if ($this->isDimension( $carray['name'] ) ) { + $dims[] = $carray['name']; + } + } + } + + return $dims; + } + + function getMetricNamesFromConstraints() { + + $metrics = array(); + foreach ($this->getConstraints() as $k => $constraint) { + + if ( $this->isMetric( $constraint['name'] ) ) { + $metrics[] = $constraint['name']; + } + } + + return $metrics; + } + + function isDimensionRelated($dimension_name, $entity_name) { + + $entity = owa_coreAPI::entityFactory($entity_name); + + $dimension = $this->lookupDimension($dimension_name, $entity); + + if ($dimension['denormalized'] === true) { + //$this->related_dimensions[$dimension['name']] = $dimension; + owa_coreAPI::debug("Dimension: $dimension_name is denormalized into $entity_name"); + return true; + } else { + + $fk = $this->getDimensionForeignKey($dimension, $entity); + + if ($fk) { + owa_coreAPI::debug("Dimension: $dimension_name is related to $entity_name"); + //$this->related_dimensions[$dimension['name']] = $dimension; + return true; + } else { + owa_coreAPI::debug("Could not find a foreign key for $dimension_name in $entity_name"); + } + } + } + + function getMetricEntities($metric_name) { + owa_coreAPI::debug("getting metric entities for $metric_name"); + + //get the class implementations + $s = owa_coreAPI::serviceSingleton(); + $classes = $s->getMetricClasses($metric_name); + + $entities = array(); + + // cycles through metric classes and get their entity names + foreach ($classes as $name => $map) { + $m = owa_coreAPI::metricFactory($map['class'], $map['params']); + + // check to see if this is a calculated metric + if ($m->isCalculated()) { + + foreach ($m->getChildMetrics() as $cmetric_name) { + $this->addCalculatedMetric($m); + $entities = array_merge($this->getMetricEntities($cmetric_name), $entities); + } + + } else { + $this->metricObjectsByEntityMap[$m->getEntityName()][$metric_name] = $m; + $entities[$metric_name][] = $m->getEntityName(); + } + + } + + return $entities; + } + + function reduceTables($new, $old) { + + return array_intersect($new, $old); + } + + function getDimensionForeignKey($dimension, $entity) { + + if ($dimension) { + //$entity = ; + $dim = $dimension; + $fk = array(); + // check for foreign key column by name if dimension specifies one + //print_r($dim); + if ( isset($dim['foreign_key_name']) && ! empty($dim['foreign_key_name'])) { + // get foreign key col by + if ($entity->isForeignKeyColumn($dim['foreign_key_name'])){ + $fk = array('col' => $dim['foreign_key_name'], 'entity' => $entity); + } + + } else { + // if not check for foreign key by entity name + //check to see if the metric's entity has a foreign key to the dimenesion table. + $fk = array(); + + $fkcol = $entity->getForeignKeyColumn($dim['entity']); + owa_coreAPI::debug("Foreign Key check: ". print_r($fkcol, true)); + if ($fkcol) { + $fk['col'] = $fkcol; + $fk['entity'] = $entity; + } + } + + return $fk; + } + } + + function isDimension( $name ) { + + $dims = owa_coreAPI::getAllDimensions(); + //print_r($dims); + return in_array( $name, array_keys( $dims ) ); + } + + function isMetric( $name ) { + + $metrics = owa_coreAPI::getAllMetrics(); + return in_array( $name, array_keys( $metrics ) ); + } + + function getDimensionByEntityName($dim_name, $entity_name) { + + $entity = owa_coreAPI::entityFactory($entity_name); + return $this->lookupDimension($dim_name, $entity); + } + + /** + * Retrieves dimension given a name and associated fact table entity. + * + * @param $name string the name of the dimenson + * @param $entity object the entity object + * @return array + */ + function lookupDimension($name, $entity) { + + // check for denormalized + $service = owa_coreAPI::serviceSingleton(); + $dim = $service->getDenormalizedDimension($name, $entity->getName()); + + if ($dim) { + //apply table aliasing to dimension column + $dim['column'] = $entity->getTableAlias().'.'.$dim['column']; + } else { + + // check for normalized dim + if (array_key_exists($name, $this->related_dimensions)) { + $dim = $this->related_dimensions[$name]; + } else { + + $dim = $service->getDimension($name); + + if ($dim) { + $dimEntity = owa_coreAPI::entityFactory($dim['entity']); + // alias needs to use fk name in case there are two joins on the + // same table. This is also used in addRelation method + $alias = $dimEntity->getTableAlias().'_via_'.$dim['foreign_key_name']; + //$dim['column'] = $dimEntity->getTableAlias().'.'.$dim['column']; + $dim['column'] = $alias.'.'.$dim['column']; + } else { + $msg = "$name is not a registered dimension."; + owa_coreAPI::debug($msg); + $this->addError($msg); + } + + } + } + + return $dim; + } + + function setLimit($value) { + + if (!empty($value)) { + + $this->limit = $value; + } + } + + function setOrder($value) { + + if (!empty($value)) { + $this->params['order'] = $value; + } + } + + function getOrder() { + + if (array_key_exists('order', $this->params)) { + return $this->params['order']; + } + } + + function setSort($column, $order) { + + //$this->params['orderby'][] = array($this->getColumnName($column), $order); + } + + function setSorts($array) { + + if (is_array($array)) { + + if (!empty($this->params['orderby'])) { + $this->params['orderby'] = array_merge($array, $this->params['orderby']); + + } else { + $this->params['orderby'] = $array; + } + } + } + + function applySorts() { + + $sorts = $this->params['orderby']; + + if ($sorts) { + + foreach ($sorts as $sort) { + + $sort_col = $sort[0]; + + if ( $this->isMetric( $sort[0] ) ) { + $sort_metric = $this->getMetricImplementation($sort[0]); + if ( $sort_metric->isCalculated() ) { + + $child_metrics = $sort_metric->getChildMetrics(); + $formula = $sort_metric->getFormula(); + + // replace metric names with unique identifiers + // so that follow on replacement doesn't clobber anything. + foreach ($child_metrics as $child) { + + $formula = str_replace($child, '__'.$child, $formula); + } + + // now replace the names with seldct statements. + foreach ($child_metrics as $child) { + $child_metric = $this->getMetricImplementation( $child ); + $select = $child_metric->getSelect(); + $formula = str_replace('__'.$child, $select[0], $formula); + } + + $sort_col = $formula; + } + } + + $this->db->orderBy($sort_col, $sort[1]); + } + } + } + + function sortStringToArray($string) { + + if ($string) { + + // add string to query params array for use in URLs. + $this->query_params['sort'] = $string; + + $sorts = explode(',', $string); + + $sort_array = array(); + + foreach ($sorts as $sort) { + + if (strpos($sort, '-')) { + $column = substr($sort, 0, -1); + $order = 'DESC'; + } else { + $column = $sort; + $order = 'ASC'; + } + + //$col_name = $this->getColumnName($column); + $check = $this->isSortValid($column); + + if ($check) { + + $col_name = $column; + + if ($col_name) { + $sort_array[$sort][0] = $col_name; + $sort_array[$sort][1] = $order; + + } else { + $this->addError("$column is not a valid column to sort on"); + } + } + } + + return $sort_array; + } + } + + function isSortValid($needle) { + + $haystack = array_merge($this->metrics, $this->dimensions); + return in_array($needle, $haystack); + } + + function setPage($value) { + + if (!empty($value)) { + + $this->page = $value; + + if (!empty($this->pagination)) { + $this->pagination->setPage($value); + } + } + } + + function setOffset($value) { + + if (!empty($value)) { + $this->params['offset'] = $value; + } + } + + function setFormat($value) { + if (!empty($value)) { + $this->format; + $this->params['result_format'] = $value; + } + } + + function setPeriod($value) { + if (!empty($value)) { + $this->params['period'] = $value; + } + } + + function setTimePeriod($period_name = '', $startDate = null, $endDate = null, $startTime = null, $endTime = null) { + + $map = false; + + if ($startDate && $endDate) { + $period_name = 'date_range'; + $map = array('startDate' => $startDate, 'endDate' => $endDate); + $dimension_name = 'date'; + $format = 'yyyymmdd'; + } elseif ($startTime && $endTime) { + $period_name = 'time_range'; + $map = array('startTime' => $startTime, 'endTime' => $endTime); + $dimension_name = 'timestamp'; + $format = 'timestamp'; + } else { + owa_coreAPI::debug('no start/end params passed to owa_metric::setTimePeriod'); + $dimension_name = 'date'; + $format = 'yyyymmdd'; + } + + // add to query params array for use in URL construction + if ($map) { + $this->query_params = array_merge($map, $this->query_params); + } else { + $this->query_params['period'] = $period_name; + } + + $p = owa_coreAPI::supportClassFactory('base', 'timePeriod'); + + $p->set($period_name, $map); + + $this->setPeriod($p); + + $start = $p->startDate->get($format); + $end = $p->endDate->get($format); + + $this->setConstraint($dimension_name, array('start' => $start, 'end' => $end), 'BETWEEN'); + + + } + + function setStartDate($date) { + + if (!empty($date)) { + $this->params['startDate'] = $date; + } + } + + function setEndDate($date) { + if (!empty($date)) { + $this->params['endDate'] = $date; + } + } + + function applyMetaDataToResults($results) { + + $new_rows = array(); + + foreach ($results as $row) { + + $new_rows[] = $this->applyMetaDataToSingleResultRow($row); + } + + return $new_rows; + } + + function applyMetaDataToSingleResultRow($row) { + + $new_row = array(); + + foreach ($row as $k => $v) { + + if (in_array($k, $this->dimensions)) { + $type = 'dimension'; + $dim = $this->lookupDimension($k, $this->baseEntity); + $data_type = $dim['data_type']; + } elseif (in_array($k, $this->metrics)){ + $type = 'metric'; + $data_type = $this->getMetric($k)->getDataType(); + } + else { + // can't throw exception here as the metrics are sometimes used to geenrate calculated metrics + // therefor no meta data is applied as this stage. + //throw new Exception($k.' is not a metric or dimension. Check the configuration!'); + } + + + + $new_row[$k] = array( + 'result_type' => $type, + 'name' => $k, + 'value' => $v, + 'formatted_value' => $this->formatValue($data_type, $v), + 'label' => $this->getLabel($k), 'data_type' => $data_type); + } + + return $new_row; + } + + function formatValue($type, $value) { + + if (array_key_exists($type, $this->formatters)) { + + $formatter = $this->formatters[$type]; + + } else { + $s = owa_coreAPI::serviceSingleton(); + $formatter = $s->getFormatter($type); + } + + // If we found a formatter, use it + if (!empty($formatter)) { + + $value = call_user_func($formatter, $value); + } + + return $value; + } + + function numberFormatter($value) { + + return number_format($value); + } + + function formatSeconds($value) { + + return date("G:i:s",mktime(0,0,($value))); + } + + function formatPercentage($value) { + + return number_format($value * 100, 2).'%'; + } + + function formatCurrency($value) { + + return owa_lib::formatCurrency( + $value, + owa_coreAPI::getSetting( 'base', 'currencyLocal' ), + owa_coreAPI::getSetting( 'base', 'currencyISO3' ) + ); + } + + /** + * Sets an individual label + * return the key so that it can be nested + * @return $key string + */ + function addLabel($key, $label) { + + $this->labels[$key] = $label; + return $key; + } + + function getLabel($key = '') { + + if (array_key_exists($key, $this->labels)) { + return $this->labels[$key]; + } else { + //owa_coreAPI::debug("No label found for $key."); + } + + } + + /** + * Retrieve the labels of the measures + * + */ + function getLabels() { + + return $this->labels; + } + + /** + * Sets an individual label + * return the key so that it can be nested + * @return $key string + */ + function setLabel($label) { + + $this->labels[$this->getName()] = $label; + } + + /** + * Set the labels of the measures + * + */ + function setLabels($array) { + + $this->labels = $array; + } + + function getPeriod() { + + return $this->params['period']; + } + + function getLimit() { + + return $this->limit; + } + + /** + * Adds a dimension to the dimension map + * + * Retrieves dimension info from service layer and checks to see if + * dimension is denromalized or if it is a valid relation + */ + function setDimension($name) { + + if ($name) { + $this->dimensions[] = $name; + } + } + + function setDimensions($array) { + + if ($array) { + + foreach($array as $name) { + + $this->setDimension($name); + } + } + } + + function dimensionsStringToArray($string) { + + // add string to query params array for use in URLs. + $this->query_params['dimensions'] = $string; + return explode(',', $string); + } + + function metricsStringToArray($string) { + + // add string to query params array for use in URLs. + $this->query_params['metrics'] = $string; + return explode(',', $string); + } + + + function dimensionsArrayToString($array) { + + return implode(',', $array); + } + + /** + * Applies dimensional sql to dao object + */ + function applyDimensions() { + + foreach ($this->dimensions as $dimension_name) { + $dim = $this->lookupDimension($dimension_name, $this->baseEntity); + // add column name to select statement + $this->db->selectColumn($dim['column'], $dim['name']); + // add groupby + $this->db->groupBy($dim['column']); + $this->addLabel($dim['name'], $dim['label']); + } + } + + function applyJoins() { + + foreach($this->related_dimensions as $dim) { + $this->addRelation($dim); + } + } + + function getBaseEntity() { + return $this->baseEntity; + } + + function addRelation($dim, $db = '', $entity = '') { + + if ( ! $db ) { + + $db = $this->db; + } + + if ( ! $entity ) { + $entity = $this->getBaseEntity(); + } + + // if denomalized, skip + if ($dim['denormalized'] === true) { + return; + } + + // have already determined base enttiy at this point so use that. + $fk = $this->getDimensionForeignKey($dim, $entity); + //print_r($fk); + //print $fk; + if ($fk) { + + // create dimension entity + $dimEntity = owa_coreAPI::entityFactory($dim['entity']); + // get foreign key column + //$bm = $this->getBaseMetric(); + //$fpk_col = $bm->entity->getProperty($fk); + $fpk_col = $fk['entity']->getProperty($fk['col']); + //$fpk_col = $this->baseEntity->getProperty($fk['col']); + + //print_r($fk['col']); + $fpk = $fpk_col->getForeignKey(); + // add join + //print_r($fpk); + // needed to make joins unique in cases where there are + // two joins onthe same table using different foreign keys. + $alias = $dimEntity->getTableAlias().'_via_'.$dim['foreign_key_name']; + //$this->db->join(OWA_SQL_JOIN, $dimEntity->getTableName(), $dimEntity->getTableAlias(), $fk['entity']->getTableAlias().'.'.$fk['col'], $dimEntity->getTableAlias().'.'.$fpk[1]); + $db->join(OWA_SQL_JOIN, $dimEntity->getTableName(), $alias, $fk['entity']->getTableAlias().'.'.$fk['col'], $alias.'.'.$fpk[1]); + + //$this->addColumn($dim['name'], $dimEntity->getTableAlias().'.'.$dim['column']); + $this->addColumn($dim['name'], $alias.'.'.$dim['column']); + + } else { + // add error result set + owa_coreAPI::debug(sprintf('%s metric does not have relation to dimension %s', $fk['entity']->getName(), $dim['name'])); + } + + } + + // remove + function addMetric($metric_name, $child = false) { + + $ret = false; + + $m = $this->getMetric($metric_name); + + if (!$m) { + $m = owa_coreAPI::metricFactory($metric_name); + + if ($m) { + + + // necessary if the metric was first added as a child but later added as a parent. + if (!$child) { + + if (array_key_exists($metric_name, $this->childMetrics)) { + unset ($this->childMetrics[$metric_name]); + } + } else { + // add child metrics to child metric maps + // check to see if it wasn't already added as a non-child metric. + if (!array_key_exists($metric_name, $this->metrics)){ + $this->childMetrics[$metric_name] = $metric_name; + } + } + + // check to see if this is a calculated metric + if ($m->isCalculated()) { + + return $this->addCalculatedMetric($m); + } + + if ($this->checkForFactTableRelation($m)) { + + $this->metrics[$metric_name] = $m; + $this->metricsByTable[$m->getTableName()] = $metric_name; + $this->addSelect($m->getSelect()); + $this->addLabel($m->getName(), $m->getLabel()); + + $ret = true; + } + + } else { + $this->addError("$metric_name is not a metric."); + } + } else { + $ret = true; + } + + + + return $ret; + } + + function addCalculatedMetric($calc_metric_obj) { + + // add label of calculated metric obj + $this->addLabel($calc_metric_obj->getName(),$calc_metric_obj->getLabel()); + // add to calculated metric map + $this->calculatedMetrics[$calc_metric_obj->getName()] = $calc_metric_obj; + + } + + function getCalculatedMetricByName($name) { + + return $this->calculatedMetrics[$name]; + } + + function addSelect($select_array) { + + $this->params['selects'][] = $select_array; + } + + //depricated? + function getSelects() { + + if (array_key_exists('selects', $this->params)) { + return $this->params['selects']; + } + } + + // can only be called after base entity is determined. + function getMetricImplementation($metric_name) { + + if (!array_key_exists($metric_name, $this->calculatedMetrics)) { + + return $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$metric_name]; + + } else { + return $this->getCalculatedMetricByName($metric_name); + } + } + + function applySelects() { + //print_r($this->metrics); + foreach($this->metrics as $k => $metric_name) { + + if (!array_key_exists($metric_name, $this->calculatedMetrics)) { + + $m = $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$metric_name]; + + $select = $m->getSelect(); + //print_r ($select); + $this->db->selectColumn($select[0], $select[1]); + } else { + $m = $this->getCalculatedMetricByName($metric_name); + } + + $this->addLabel($m->getName(), $m->getLabel()); + } + + // add selects for calculated metrics + if (!empty($this->calculatedMetrics)) { + + // loop through calculated metric objects + foreach ($this->calculatedMetrics as $cmetric) { + //create child metrics + foreach( $cmetric->getChildMetrics() as $child_name) { + // check to see if the metric has already been added + if (!in_array($child_name, $this->metrics)) { + + $child = $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$child_name]; + $select = $child->getSelect(); + //print_r ($select[0]); + $this->db->selectColumn($select[0], $select[1]); + // needed so we can remove this temp metric later + $this->childMetrics[] = $child_name; + owa_coreAPI::debug("Added $child_name to ChildMetrics array"); + } + } + } + } + } + + function getFormat() { + + if (array_key_exists('result_format', $this->params)) { + return $this->params['result_format']; + } + } + + function getColumnName($string) { + + //$string = trim($string); + if (array_key_exists($string, $this->related_dimensions)) { + return $this->related_dimensions[$string]['column']; + } + + if (array_key_exists($string, $this->related_metrics)) { + return $string; + } + + + //return $string; + + } + + /** + * Sets a metric's column name into the all_columns map + * + * this is needed when combining metrics so that sort and + * constraint column names can be looked up fro ma single map. + * + * NEEDED??? + */ + function addColumn($name, $col) { + + $this->all_columns[$name] = $col; + } + + function addError($msg) { + + $this->errors[] = $msg; + owa_coreAPI::debug($msg); + } + + /** + * Generates a result set for the metric + * + */ + function getResults() { + + // get paginated result set object + $rs = owa_coreAPI::supportClassFactory('base', 'paginatedResultSet'); + + $bm = $this->chooseBaseEntity(); + + if ($bm) { + + $bname = $bm->getName(); + + owa_coreAPI::debug("Using $bname as base entity for making result set."); + + // set constraints + $this->applyJoins(); + owa_coreAPI::debug('about to apply constraints'); + $this->applyConstraints(); + owa_coreAPI::debug('about to apply selects'); + $this->applySelects(); + + // set from table + if ( $this->segment ) { + $this->db->selectFrom( $this->generateSegmentQuery( $bm ), $bm->getTableAlias() ); + } else { + $this->db->selectFrom($bm->getTableName(), $bm->getTableAlias()); + } + + // generate aggregate results + $results = $this->db->getOneRow(); + // merge into result set + if ($results) { + $rs->aggregates = array_merge($this->applyMetaDataToSingleResultRow($results), $rs->aggregates); + } + + // setup dimensional query + if (!empty($this->dimensions)) { + + $this->applyJoins(); + // apply dimensional SQL + $this->applyDimensions(); + + $this->applySelects(); + + // set from table + if ( $this->segment ) { + $this->db->selectFrom( $this->generateSegmentQuery( $bm ), $bm->getTableAlias() ); + } else { + $this->db->selectFrom($bm->getTableName(), $bm->getTableAlias()); + } + + // pass limit to db object if one exists + if (!empty($this->limit)) { + $rs->setLimit($this->limit); + } + // pass limit to db object if one exists + if (!empty($this->page)) { + $rs->setPage($this->page); + } + + $this->applyConstraints(); + + if (array_key_exists('orderby', $this->params)) { + $sorts = $this->params['orderby']; + // apply sort by + if ($sorts) { + $this->applySorts(); + foreach ($sorts as $sort) { + //$this->db->orderBy($sort[0], $sort[1]); + $rs->sortColumn = $sort[0]; + if (isset($sort[1])){ + $rs->sortOrder = strtolower($sort[1]); + } else { + $rs->sortOrder = 'asc'; + } + } + } + } + + // add labels + $rs->setLabels($this->getLabels()); + + // generate dimensonal results + $results = $rs->generate($this->db); + + $rs->resultsRows = $this->applyMetaDataToResults($results); + } + + // add labels + $rs->setLabels($this->getLabels()); + + // add period info + + $rs->setPeriodInfo($this->params['period']->getAllInfo()); + + $rs = $this->computeCalculatedMetrics($rs); + + // add urls + $urls = $this->makeResultSetUrls(); + $rs->self = $urls['self']; + + if ($rs->more) { + + $rs->next = $urls['next']; + } + + if ($this->page >=2) { + $rs->previous = $urls['previous']; + } + + $rs->createResultSetHash(); + } + + $rs->errors = $this->errors; + + $rs->setRelatedDimensions( $this->getAllRelatedDimensions( $bm ) ); + $rs->setRelatedMetrics( $this->getAllRelatedMetrics( $bm ) ); + + return $rs; + } + + function generateSegmentQuery( $base_entity ) { + + $segment = $this->getSegment(); + $segment_entity = owa_coreAPI::entityFactory($base_entity->getName()); + $segment_entity->setTableAlias( $segment_entity->getTableAlias() . '_segment'); + + if ( $segment ) { + // use a new data access object + $db = owa_coreAPI::dbFactory(); + $db->select( $segment_entity->getTableAlias().'.*' ); + $db->from( $segment_entity->getTableName(), $segment_entity->getTableAlias() ); + + if ( isset( $segment['metrics'] ) ) { + + //$this->applyConstraints( $segment['metrics'], $db); + } + + if ( isset( $segment['dimensions'] ) ) { + //print_r($segment); + foreach ($segment['dimensions'] as $k => $dim) { + + $check = $this->isDimensionRelated($dim['name'], $segment_entity->getName() ); + if ( $check ) { + $dimension = $this->lookupDimension($dim['name'], $segment_entity); + + if ( ! isset($dimension['denormalized'] ) || $dimension['denormalized'] != true ) { + $this->addRelation($dimension, $db, $segment_entity); + } + } + } + //print_r( $segment['dimensions'] ); + $this->applyConstraints( $segment['dimensions'], $db, $segment_entity); + + // apply siteId, startDate, and endDate constraints + $constraint_names = array('siteId', 'date'); + $constraints_apply = array(); + //print_r($this->params['constraints']); + foreach ( $constraint_names as $name ) { + + $con = $this->getConstraint( $name ); + if ( $con ) { + $constraints_apply[$name] = $con; + } + } + + if ( $constraints_apply ) { + $this->applyConstraints( $constraints_apply, $db, $segment_entity); + } + } + + return sprintf('(%s)', $db->generateSelectQuerySql() ); + } + + } + + function computeCalculatedMetrics($rs) { + + foreach ($this->calculatedMetrics as $cm) { + + // add aggregate metric + $formula = $cm->getFormula(); + $div_by_zero = false; + + //owa_coreAPI::debug( "checking calculated metrics..." ); + //owa_coreAPI::debug( $rs->aggregates ); + foreach ($cm->getChildMetrics() as $metric_name) { + + $ag_value = $rs->getAggregateMetric($metric_name); + + if (empty($ag_value) || $ag_value == 0) { + $ag_value = 0; + $div_by_zero = true; + } + + $formula = str_replace($metric_name, $ag_value, $formula); + } + + if ( ! $div_by_zero ) { + $value = $this->evalFormula($formula); + } else { + $value = 0; + } + + $rs->setAggregateMetric($cm->getName(), $value, $cm->getLabel(), $cm->getDataType(), $this->formatValue($cm->getDataType(), $value)); + + // add dimensional metric + + if ($rs->getRowCount() > 0) { + + foreach ($rs->resultsRows as $k => $row) { + + // add aggregate metric + $formula = $cm->getFormula(); + $row_div_by_zero = false; + foreach ($cm->getChildMetrics() as $metric_name) { + + if (array_key_exists($metric_name, $row)) { + $row_value = $row[$metric_name]['value']; + } else { + $row_value = ''; + } + if (empty($row_value) || $row_value == 0) { + $row_value = 0; + $row_div_by_zero = true; + } + + $formula = str_replace($metric_name, $row_value, $formula); + + } + + if ( ! $row_div_by_zero ) { + $value = $this->evalFormula($formula); + } else { + $value = 0; + } + + $rs->appendRow($k, 'metric', $cm->getName(), $value, $cm->getLabel(), $cm->getDataType(), $this->formatValue($cm->getDataType(), $value)); + } + } + } + + // clean up by removing child metrics before returning the result set. + foreach ($this->childMetrics as $metric_name) { + + $rs->removeMetric($metric_name); + } + + return $rs; + } + + function evalFormula($formula) { + + //safety first. should only be computing numbers. + $formula = str_replace('$','', $formula); + + // need parens and @ to handle divsion by zero errors + $formula = '$value = ('.$formula.');'; + //print $formula; + // calc + @ eval($formula); + + if (!$value) { + $value = 0; + } + + return $value; + } + + /** + * Return the approraite metric implementation for the baseEntity + * Must be called after the base entity has been determined + * + * @param string $name the name of the metric + * + */ + function getMetric($name) { + + // check to see if the entity object map is loaded + if ( ! in_array( $name, $this->metrics ) ) { + // if not load it forthat metric + $this->getMetricEntities($name); + } + + return $this->metricObjectsByEntityMap[$this->baseEntity->getName()][$name]; + + } + + + + function setQueryStringParam($name, $string) { + + $this->query_params[$name] = $string; + } + + function makeResultSetUrls() { + + $urls = array(); + // get api url + $api_url = owa_coreAPI::getSetting('base', 'api_url'); + // get base query params + $query_params = $this->query_params; + // add api command + $query_params['do'] = 'getResultSet'; + //add format + if ($this->format) { + $query_params['format'] = $this->format; + } else { + $query_params['format'] = 'json'; + } + // add current page if any + if ($this->page) { + $query_params['page'] = $this->page; + } + // add limit + if ($this->limit) { + $query_params['resultsPerPage'] = $this->limit; + } + + // build url for this result set + $link_template = owa_coreAPI::getSetting('base', 'link_template'); + $q = $this->buildQueryString($query_params); + $urls['self'] = sprintf($link_template, $api_url, $q); + + // build url for next page of result set + $next_query_params = $query_params; + if ($this->page) { + $next_query_params['page'] = $query_params['page'] + 1; + } else { + $next_query_params['page'] = 2; + } + + $nq = $this->buildQueryString($next_query_params); + $urls['next'] = sprintf($link_template, $api_url, $nq); + + // build previous url if page is greater than 2 + if ($this->page >= 2) { + $previous_query_params = $query_params; + $previous_query_params['page'] = $query_params['page'] - 1; + $pq = $this->buildQueryString($previous_query_params); + $urls['previous'] = sprintf($link_template, $api_url, $pq); + } + + $base_query_params = $this->query_params; + $base_query_params['format'] = $this->format; + + // build pagination url template for use in constructing + $q = $this->buildQueryString($base_query_params); + $url['base_url'] = sprintf($link_template, $api_url, $q); + + return $urls; + } + + function buildQueryString($params, $seperator = '&') { + + $new = array(); + //get namespace + $ns = owa_coreAPI::getSetting('base', 'ns'); + foreach ($params as $k => $v) { + + $new[$ns.$k] = $v; + } + + return http_build_query($new,'', $seperator); + } + + function getAllRelatedDimensions($entity) { + + $s = owa_coreAPI::serviceSingleton(); + $dims = array(); + $denormalized_dims = $s->denormalizedDimensions; + + foreach ( $denormalized_dims as $ddim_imp) { + + foreach ( $ddim_imp as $k => $ddim) { + + if ($k === $entity->getName()) { + $dims[ $ddim['family'] ][] = array( 'name' => $ddim['name'], 'label' => $ddim['label'] ); + } + } + } + + $normalized_dims = $s->dimensions; + + foreach ( $normalized_dims as $k => $ndim ) { + + // check to see if realation exists with dim's speficied foreign key + $fk = $ndim['foreign_key_name']; + if ( $fk ) { + + $col_exists = $entity->getProperty($fk); + + } else { + // check to see if there is any foreign key to the dim's entity + $col_exists = $entity->getForeignKeyColumn( $ndim['entity'] ); + } + + if ( $col_exists ) { + $dims[ $ndim['family'] ][] = array( 'name' => $ndim['name'], 'label' => $ndim['label'] ); + } + } + + return $dims; + } + + function getAllRelatedMetrics( $entity ) { + + $related_metrics = array(); + $s = owa_coreAPI::serviceSingleton(); + $all_metrics = $s->getAllMetrics(); + $entity_name = $entity->getName(); + $s = owa_coreAPI::serviceSingleton(); + $metricsByEntity = $s->getMap('metricsByEntity'); + foreach ($all_metrics as $metric_name => $implementations) { + + foreach ($implementations as $implementation) { + + $m = owa_coreAPI::metricFactory( $implementation['class'], $implementation['params'] ); + + if ( $m->isCalculated() ) { + + $children = $m->getChildMetrics(); + $error = false; + foreach( $children as $child ) { + + if ( ! isset($metricsByEntity[$entity_name][$child])) { + + $error = true; + } + } + + if ( ! $error ) { + + $related_metrics[$implementation['group']][] = array( + 'name' => $metric_name, + 'label' => $implementation['label'], + 'description' => $implementation['description'], + 'group' => $implementation['group'] + ); + + continue; + } + + + } else { + + if ( $entity_name === $m->getEntityName() ) { + + $related_metrics[$implementation['group']][] = array( + 'name' => $metric_name, + 'label' => $implementation['label'], + 'description' => $implementation['description'], + 'group' => $implementation['group'] + ); + + continue; + } + } + } + } + + return $related_metrics; + } } diff --git a/modules/base/classes/sanitize.php b/modules/base/classes/sanitize.php index 71737e223..76b97cb0e 100644 --- a/modules/base/classes/sanitize.php +++ b/modules/base/classes/sanitize.php @@ -26,354 +26,354 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 + * @version $Revision$ + * @since owa 1.3.0 */ class owa_sanitize { - - /** - * Remove Non alpha or numeric characters - * - * @param string|array $input String or array contain input to sanitize. - * @param array $exceptions An array of additional characters that should be allowed. - * @return string|array $sanitzed A Santized string or array - */ - public static function removeNonAlphaNumeric($input, $exceptions = array()) { - - $allow = ''; - - // add exceptions to allowed char part of regex - if ( !empty( $exceptions ) ) { - foreach ( $exceptions as $value ) { - $allowed_chars .= "\\$value"; - } - } - - $regex = "/[^{$allowed_chars}a-zA-Z0-9]/"; - - // check to see if string is an array - if ( is_array ( $input ) ) { - $sanitized = array(); - foreach ( $input as $key => $item ) { - $sanitized[$key] = preg_replace( $regex, '', $item ); - } - // assume input is a singel string - } else { - $sanitized = preg_replace( $regex, '', $input ); - } - - return $sanitized; - } - - /** - * Escapes a string for use in display output - * - * @param string $string The string to be escaped - * @param string $encoding The charset to use in encoding. - * @param string $quotes The php constant for encodig quotations used by htmlentities - * @return string html encoded string - * @link http://www.php.net/manual/en/function.htmlentities.php - * @access public - */ - public static function escapeForDisplay($string, $encoding = 'UTF-8', $quotes = '') { - - if (!$quotes) { - //use mode to ocnvert both single and double quotes. - $quotes = ENT_QUOTES; - } - - // revert special chars, some values are saved encoded in the database eg. page title - $string = html_entity_decode($string, $quotes); - - return htmlentities($string, $quotes, $encoding); - } - - - /** - * Strip Whitespace - * - * @param string $str String to strip - * @return string whitespace sanitized input - * @access public - */ - public static function stripWhitespace( $input ) { - - $output = preg_replace( '/[\n\r\t]+/', '', $input ); - return preg_replace( '/\s{2,}/', ' ', $output ); - } - - /** - * Strip IMG html tags - * - * @param string $input String to sanitize - * @return string String with no img tags - * @access public - */ - public static function stripImages( $input ) { - - $output = preg_replace('/(]*>)(]+alt=")([^"]*)("[^>]*>)(<\/a>)/i', '$1$3$5
', $input); - $output = preg_replace('/(]+alt=")([^"]*)("[^>]*>)/i', '$2
', $output); - $output = preg_replace('/]*>/i', '', $output); - return $output; - } - - /** - * Strip Scripts and Stylesheets - * - * @param string $input String to sanitize - * @return string String with - - - - - - - - - - - - - - - - - - - - - - setTemplate($table_row_template));?> - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + setTemplate($table_row_template));?> + + + + + + + +
- -
No data to display.
- + +
No data to display.
+ \ No newline at end of file diff --git a/modules/base/templates/header.tpl b/modules/base/templates/header.tpl index 0eba96d2c..84a6e5d29 100644 --- a/modules/base/templates/header.tpl +++ b/modules/base/templates/header.tpl @@ -1,38 +1,38 @@ -
- - -   - - - - getCurrentUser(); ?> - - Hi, out( $cu->getUserData('user_id') );?> ! • - - - - - - - - - - -
- -
- - - headerActions(); ?> - +
+ + +   + + + + getCurrentUser(); ?> + + Hi, out( $cu->getUserData('user_id') );?> ! • + + + + + + + + + + +
+ +
+ + + headerActions(); ?> +
\ No newline at end of file diff --git a/modules/base/templates/install.tpl b/modules/base/templates/install.tpl index bfa71a281..b768e45bb 100644 --- a/modules/base/templates/install.tpl +++ b/modules/base/templates/install.tpl @@ -1,8 +1,8 @@ -
-
-

Open Web Analytics Installer

-
-
-
- -
+
+
+

Open Web Analytics Installer

+
+
+
+ +
diff --git a/modules/base/templates/install_check_env.tpl b/modules/base/templates/install_check_env.tpl index 15ab4dec2..0ae31b33d 100644 --- a/modules/base/templates/install_check_env.tpl +++ b/modules/base/templates/install_check_env.tpl @@ -1,22 +1,22 @@ - - -

Uh-oh. We found a few issues.

- -

We found a few problems with your server environment. Please resolve these issues and start the installation again.

- - - -

Problems

- -

- - - -

- + + +

Uh-oh. We found a few issues.

+ +

We found a few problems with your server environment. Please resolve these issues and start the installation again.

+ + + +

Problems

+ +

+ + + +

+ diff --git a/modules/base/templates/install_config_entry.php b/modules/base/templates/install_config_entry.php index 0968f1f2f..29b7db80d 100644 --- a/modules/base/templates/install_config_entry.php +++ b/modules/base/templates/install_config_entry.php @@ -3,73 +3,73 @@ We could not locate OWA's owa-config.php configuration file. You can use the form below to create the file but this may not work on all hosts. If file generation fails, you can just create it manually by renaming owa-config-dist.php to owa-config.php and filling in your database information and public URL.

-
- -

Web URL of OWA

-

- URL of OWA: - - - - This is the web URL of OWA's base directory. -

- -

Database

-

- Database Type: - - - - This is the type of database you are going to use. -

- -

- Database Host: - - - - This is the host that your database resides on. Localhost is ok. -

+ + +

Web URL of OWA

+

+ URL of OWA: + + + + This is the web URL of OWA's base directory. +

+ +

Database

+

+ Database Type: + + + + This is the type of database you are going to use. +

+ +

+ Database Host: + + + + This is the host that your database resides on. Localhost is ok. +

Database Port: - - + + This optional setting is used to change the port for your database. OWA will use the default port 3306 if you leave this empty.

- -

- Database Name: - - - - This is the name of the database to install tables into. -

- -

- Database User: - - - - This is the user name to connect to the database. -

- -

- Database Password: - - - - This is the password to connect to the database. -

-

- createNonceFormField('base.installConfig');?> - - -

- -

- + +

+ Database Name: + + + + This is the name of the database to install tables into. +

+ +

+ Database User: + + + + This is the user name to connect to the database. +

+ +

+ Database Password: + + + + This is the password to connect to the database. +

+

+ createNonceFormField('base.installConfig');?> + + +

+ + +

\ No newline at end of file diff --git a/modules/base/templates/install_defaults_entry.php b/modules/base/templates/install_defaults_entry.php index 85d43af07..c59005f68 100644 --- a/modules/base/templates/install_defaults_entry.php +++ b/modules/base/templates/install_defaults_entry.php @@ -1,50 +1,50 @@ -

Default Site & User Information

-
-
- -

- Site Domain - - - - - This is the domain of the site to track. -

- -

- Your Admin Name - - - - This is name of the admin user. -

- -

- Your E-mail Address - - - - This is the e-mail address of the admin user. -

- -

- Your Password - - - - This will be the password of the admin user. -

- -

- createNonceFormField('base.installBase');?> - - -

- -
- -
- \ No newline at end of file +

Default Site & User Information

+
+
+ +

+ Site Domain + + + + + This is the domain of the site to track. +

+ +

+ Your Admin Name + + + + This is name of the admin user. +

+ +

+ Your E-mail Address + + + + This is the e-mail address of the admin user. +

+ +

+ Your Password + + + + This will be the password of the admin user. +

+ +

+ createNonceFormField('base.installBase');?> + + +

+ +
+ +
+ \ No newline at end of file diff --git a/modules/base/templates/install_finish.tpl b/modules/base/templates/install_finish.tpl index 40552278a..168144b97 100644 --- a/modules/base/templates/install_finish.tpl +++ b/modules/base/templates/install_finish.tpl @@ -1,20 +1,20 @@
- -

Success! That's It. Installation is Complete.

-

Open Web Analytics has been successfully installed. Login using the user name and password below and generate a tracker.

-

- User Name: - -

-

- Password: - - -

-
-

- "base.sitesInvocation", "siteId" => $site_id), false, owa_coreAPI::getSetting('base','public_url'));?>" target="_blank"> - Login and generate a site tracker! - -

+ +

Success! That's It. Installation is Complete.

+

Open Web Analytics has been successfully installed. Login using the user name and password below and generate a tracker.

+

+ User Name: + +

+

+ Password: + + +

+
+

+ "base.sitesInvocation", "siteId" => $site_id), false, owa_coreAPI::getSetting('base','public_url'));?>" target="_blank"> + Login and generate a site tracker! + +

\ No newline at end of file diff --git a/modules/base/templates/install_finish_embedded.tpl b/modules/base/templates/install_finish_embedded.tpl index e0b29fc44..c5a78a528 100644 --- a/modules/base/templates/install_finish_embedded.tpl +++ b/modules/base/templates/install_finish_embedded.tpl @@ -1,8 +1,8 @@
- -

Installation is complete. That's it, you made it!

- -

From here you can configure OWA's settings, or view your analytics.

- - + +

Installation is complete. That's it, you made it!

+ +

From here you can configure OWA's settings, or view your analytics.

+ +

\ No newline at end of file diff --git a/modules/base/templates/install_schema_detected.tpl b/modules/base/templates/install_schema_detected.tpl index 6a3127deb..9c9fe878c 100644 --- a/modules/base/templates/install_schema_detected.tpl +++ b/modules/base/templates/install_schema_detected.tpl @@ -1,14 +1,14 @@
- -

Whoops. It looks like OWA is already installed!

- -

To re-install OWA, drop all owa_ tables run the installer again.

-
-

- "base.loginForm"), false, owa_coreAPI::getSetting('base','public_url'));?>"> - Login - -

- + +

Whoops. It looks like OWA is already installed!

+ +

To re-install OWA, drop all owa_ tables run the installer again.

+
+

+ "base.loginForm"), false, owa_coreAPI::getSetting('base','public_url'));?>"> + Login + +

+
\ No newline at end of file diff --git a/modules/base/templates/install_start.tpl b/modules/base/templates/install_start.tpl index 42a739886..3db87f331 100644 --- a/modules/base/templates/install_start.tpl +++ b/modules/base/templates/install_start.tpl @@ -1,15 +1,15 @@
-

Welcome to the Installer!

- -

The next few screens will guide you through installing the Open Web Analytics framework. If at any time you - need help, please consult the config['wiki_url'];?>>OWA Wiki.

-
-

- Let's Get Started... -

- - - +

Welcome to the Installer!

+ +

The next few screens will guide you through installing the Open Web Analytics framework. If at any time you + need help, please consult the config['wiki_url'];?>>OWA Wiki.

+
+

+ Let's Get Started... +

+ + +
\ No newline at end of file diff --git a/modules/base/templates/install_start_embedded.tpl b/modules/base/templates/install_start_embedded.tpl index 9d9f9c4a2..81c396c61 100644 --- a/modules/base/templates/install_start_embedded.tpl +++ b/modules/base/templates/install_start_embedded.tpl @@ -1,33 +1,33 @@
-

- - It looks like the Open Web Analytics database still needs to be installed. -

- -
- - - - - - - - - - - - - - - - -
- - -

-

If at any time you need help, please consult the config['wiki_url'];?>>OWA Wiki.

- - +

+ + It looks like the Open Web Analytics database still needs to be installed. +

+ +
+ + + + + + + + + + + + + + + + +
+ + +

+

If at any time you need help, please consult the config['wiki_url'];?>>OWA Wiki.

+ +
\ No newline at end of file diff --git a/modules/base/templates/invocation.tpl b/modules/base/templates/invocation.tpl index 9b8b75042..1be69ff4d 100644 --- a/modules/base/templates/invocation.tpl +++ b/modules/base/templates/invocation.tpl @@ -1,36 +1,36 @@ -
- Javascript -
-

To track page views using Javascript, cut and paste this tracking tag into the HTML of your web pages. Learn more about how to use OWA's Javascript tracking API to track your web site and pages.

- - -
-
- -
- PHP -
- -

To track page views using PHP, cut and paste the following code to your PHP script/application. Learn more about how to use OWA's PHP Tracking API to track your web site and pages.

- - - -
-
- +
+ Javascript +
+

To track page views using Javascript, cut and paste this tracking tag into the HTML of your web pages. Learn more about how to use OWA's Javascript tracking API to track your web site and pages.

+ + +
+
+ +
+ PHP +
+ +

To track page views using PHP, cut and paste the following code to your PHP script/application. Learn more about how to use OWA's PHP Tracking API to track your web site and pages.

+ + + +
+
+ diff --git a/modules/base/templates/item_document.php b/modules/base/templates/item_document.php index 8a0184bda..3f1b7b838 100644 --- a/modules/base/templates/item_document.php +++ b/modules/base/templates/item_document.php @@ -1,13 +1,13 @@
-
- -
-
-
get('page_title');?>
-
- get('url');?>   Visit Site » -
-
Page Type: get('page_type');?>
-
-
+
+ +
+
+
get('page_title');?>
+
+ get('url');?>   Visit Site » +
+
Page Type: get('page_type');?>
+
+
\ No newline at end of file diff --git a/modules/base/templates/js_helper_tags.tpl b/modules/base/templates/js_helper_tags.tpl index 536aeb736..705c69241 100644 --- a/modules/base/templates/js_helper_tags.tpl +++ b/modules/base/templates/js_helper_tags.tpl @@ -1,12 +1,12 @@ - - -getValue( 'first_hit_tag', $options ) ):?> - - - - + + +getValue( 'first_hit_tag', $options ) ):?> + + + + \ No newline at end of file diff --git a/modules/base/templates/js_log_tag.tpl b/modules/base/templates/js_log_tag.tpl index bd5379221..3eff979c2 100644 --- a/modules/base/templates/js_log_tag.tpl +++ b/modules/base/templates/js_log_tag.tpl @@ -1,39 +1,39 @@ -getValue( 'no_script_wrapper', $options ) ) { ?> - - - +getValue( 'no_script_wrapper', $options ) ) { ?> + + + \ No newline at end of file diff --git a/modules/base/templates/js_report_templates.php b/modules/base/templates/js_report_templates.php index 384b1f4d3..a3af4a8ea 100644 --- a/modules/base/templates/js_report_templates.php +++ b/modules/base/templates/js_report_templates.php @@ -1,10 +1,10 @@ @@ -13,7 +13,7 @@ cell"><*= this.value *> - + ]]> @@ -21,7 +21,7 @@ <*= this.columns*> - + ]]> @@ -29,9 +29,9 @@ " class="simpleTable"> - - <*= this.headers *> - + + <*= this.headers *> + ]]> diff --git a/modules/base/templates/json.php b/modules/base/templates/json.php index e67e077fd..d6733f108 100644 --- a/modules/base/templates/json.php +++ b/modules/base/templates/json.php @@ -1,5 +1,5 @@ \ No newline at end of file diff --git a/modules/base/templates/kml_network_link_geolocation.tpl b/modules/base/templates/kml_network_link_geolocation.tpl index 0c8240057..28731cb03 100644 --- a/modules/base/templates/kml_network_link_geolocation.tpl +++ b/modules/base/templates/kml_network_link_geolocation.tpl @@ -1,21 +1,21 @@ - - - - - Open Web Analytics Links - 1 - 1 - These are network links for OWA. - - - 1 - 0 - Visits for - 0 - 1 - - makeAbsoluteLink(array('do' => 'base.kmlVisitsGeolocation', 'rand' => rand()), true, '', true);?> - - - + + + + + Open Web Analytics Links + 1 + 1 + These are network links for OWA. + + + 1 + 0 + Visits for + 0 + 1 + + makeAbsoluteLink(array('do' => 'base.kmlVisitsGeolocation', 'rand' => rand()), true, '', true);?> + + + \ No newline at end of file diff --git a/modules/base/templates/kml_visits_geolocation.tpl b/modules/base/templates/kml_visits_geolocation.tpl index 316d9348f..e6468ff47 100644 --- a/modules/base/templates/kml_visits_geolocation.tpl +++ b/modules/base/templates/kml_visits_geolocation.tpl @@ -1,20 +1,20 @@ - - - - - OWA: Visits to - Site visits for - - - - - / at : - ]]> - - ,,5000 - - #defaultStyle - - - - + + + + + OWA: Visits to + Site visits for + + + + - / at : + ]]> + + ,,5000 + + #defaultStyle + + + + \ No newline at end of file diff --git a/modules/base/templates/kpiInfobox.php b/modules/base/templates/kpiInfobox.php index 5f62f2ae6..c619b4e3f 100644 --- a/modules/base/templates/kpiInfobox.php +++ b/modules/base/templates/kpiInfobox.php @@ -4,8 +4,8 @@
-

out( $this->get( 'label' ) ); ?>

-

out( $this->get( 'number' ), false ); ?>

+

out( $this->get( 'label' ) ); ?>

+

out( $this->get( 'number' ), false ); ?>

get( 'link' ) ): ?> diff --git a/modules/base/templates/login_form.tpl b/modules/base/templates/login_form.tpl index a2db7b444..820b6c948 100644 --- a/modules/base/templates/login_form.tpl +++ b/modules/base/templates/login_form.tpl @@ -1,33 +1,33 @@
-
Login

- -
- - -
- -
- -
User Name:
-

-
Password:
-

- - -
- -
-
- -
- -
- - -
- - Forgot your password? - +
Login

+ +
+ + +
+ +
+ +
User Name:
+

+
Password:
+

+ + +
+ +
+
+ +
+ +
+ + +
+ + Forgot your password? +
diff --git a/modules/base/templates/map_dom.tpl b/modules/base/templates/map_dom.tpl index 2e5a43cc3..c7eb101e0 100644 --- a/modules/base/templates/map_dom.tpl +++ b/modules/base/templates/map_dom.tpl @@ -1,8 +1,8 @@ config['google_maps_api_key'])):?> - +
- You must have a Google Maps API Key to use this feature. Google provides this key for free at this Google web site. Once you obtain a key enter in on the profile page for this tracked web site. + You must have a Google Maps API Key to use this feature. Google provides this key for free at this Google web site. Once you obtain a key enter in on the profile page for this tracked web site.
diff --git a/modules/base/templates/metricInfobox.php b/modules/base/templates/metricInfobox.php index 6961ca16b..f61eaef40 100644 --- a/modules/base/templates/metricInfobox.php +++ b/modules/base/templates/metricInfobox.php @@ -1,5 +1,5 @@
-

getlabel($count->aggregates[$metric_name]['name']);?>

-

aggregates[$metric_name]['value'];?>

-

displaySeriesAsSparkline($count->aggregates[$metric_name]['name'], $trend, $dom_id);?>

+

getlabel($count->aggregates[$metric_name]['name']);?>

+

aggregates[$metric_name]['value'];?>

+

displaySeriesAsSparkline($count->aggregates[$metric_name]['name'], $trend, $dom_id);?>

\ No newline at end of file diff --git a/modules/base/templates/new_session_email.tpl b/modules/base/templates/new_session_email.tpl index c9befb238..bfc438c02 100644 --- a/modules/base/templates/new_session_email.tpl +++ b/modules/base/templates/new_session_email.tpl @@ -3,10 +3,10 @@

Visitor ID:

Username (email): () + echo $session['user_email']; + } else { + echo 'not set'; + } ?>)

Host:

diff --git a/modules/base/templates/options.tpl b/modules/base/templates/options.tpl index d39b70143..d7012d59e 100644 --- a/modules/base/templates/options.tpl +++ b/modules/base/templates/options.tpl @@ -1,32 +1,32 @@ -
- - - - - - - - - - - - - -
- out( $headline );?> -
-

You are using Open Web Analytics out(OWA_VERSION);?>

-

Open Web Analytics has several configuration options that can be set using the controls below. Once changes are made click the "save" button to save the configuration to the database. To learn more about configuring OWA, visit the OWA Wiki

-
-
+
+ + + + + + + + + + + + + +
+ out( $headline );?> +
+

You are using Open Web Analytics out(OWA_VERSION);?>

+

Open Web Analytics has several configuration options that can be set using the controls below. Once changes are made click the "save" button to save the configuration to the database. To learn more about configuring OWA, visit the OWA Wiki

+
+
diff --git a/modules/base/templates/options_db.tpl b/modules/base/templates/options_db.tpl index 5ecd2b138..9a5a28701 100644 --- a/modules/base/templates/options_db.tpl +++ b/modules/base/templates/options_db.tpl @@ -3,39 +3,39 @@
- Database Options - -
- Asynchronous Event Handling Mode: - -
- -
- - Event Log File Directory:
- -
- -
- - Event Log File Name:
- -
- + Database Options + +
+ Asynchronous Event Handling Mode: + +
+ +
+ + Event Log File Directory:
+ +
+ +
+ + Event Log File Name:
+ +
+
- -
- - - - + +
+ + + +
\ No newline at end of file diff --git a/modules/base/templates/options_errors.tpl b/modules/base/templates/options_errors.tpl index c8165632c..8efae6976 100644 --- a/modules/base/templates/options_errors.tpl +++ b/modules/base/templates/options_errors.tpl @@ -1,24 +1,24 @@

-
+ -
- Error Logging - -
- Logging Mode: - - -
- -
- - - +
+ Error Logging + +
+ Logging Mode: + + +
+ +
+ + +
\ No newline at end of file diff --git a/modules/base/templates/options_general.tpl b/modules/base/templates/options_general.tpl index 96a28622f..ba8347335 100644 --- a/modules/base/templates/options_general.tpl +++ b/modules/base/templates/options_general.tpl @@ -1,273 +1,273 @@ -
- -
- -
- -
- Request Processing Options - -
-
Resolve Host Names
-
Controls the resolution of host names (e.g. verizon.com) from visitor's raw IP addresses.
-
- -
-
- -
-
Log Requests From Feed Readers
-
Controls the logging of page requests made by Feed Readers. This setting must be enabled in order to compile statistics about your site's feeds.
-
- -
-
- -
-
Log Requests From Known Robots
-
Controls the logging of page requests made by known robots and spiders. Turning this feature on will dramatically increase the number of requests that are processed and logged.
-
- -
-
- -
-
Log Requests From Named Users
-
Controls the logging of requests made by named users.
-
- -
-
- -
-
Excluded IP Addresses
-
Enter a comma seperated list of the IP addresses that you wish to exclude from tracking.
-
-
- -
-
Anonymize IP Addresses
-
Anonymizes the IP addresses of visitors by removing the last octet from their IP address.
-
- -
-
- - - -
-
Fetch Referring Web Page Info
-
Controls whether OWA should crawl the web pages that refer visitors to your web site and extract descriptive meta-data that will be used in reporting.
-
- -
-
- -
-
P3P Compact Privacy Policy
-
This setting controls the P3P compact privacy policy that is returned to the browser when OWA sets cookies. Click here for more information on compact privacy policies and choosing the right one for your web site.
-
-
- -
-
URL Parameters
-
This setting controls the URL parameters that OWA should ignore when processing requests. This is useful for avoiding duplicate URLs due to the use of tracking or others state parameters in your URLs. Parameter names should be separated by comma.
-
-
- -
- -
- -
- Visitor Announcements - -
-
Announce New Visitors Via E-mail
-
Announces each new visitor to your web site via e-mail. If you have a lot of visitors then you probably want to keep this feature turned off.
-
- -
-
- -
-
Notice E-mail Address
-
This is the e-mail address that new visitor e-mails will be sent to.
-
- -
- -
- - -
- -
- - Geo-location - -
-
Perform Geo-location Lookup
-
Lookup the geographic location of visitors.
-
- -
-
- -
- -
- -
- Feed Tracking - -
-
Feed Link Tracking
-
Adds tracking parameters to RSS or Atom feeds links. This provides a way to track how many visitors come from your feeds.
-
- -
-
- -
- -
- -
- Event Queueing - -
-
Event Log File Directory
-
This is the file system path of the file that OWA will write queued events to when Event Queuing mode is turned on. (e.g. /path/to/owa/log/file.txt)
-
-
- -
- -
- - -
- Object Cache - -
-
Cache Control
-
Enables and disables object caching. This will improve performance under high load conditions. The object cache can be turned on/off via your config file. -
-
- Status: ONOFF
-
- -
-
Flush Cache
-
Flushes the object cache
- -
- - -
- -
- -
- - Reporting - - -
-
Reporting Timezone
-
This is the timezone that should be used to generate statistics for a specific time period.
-
- - - -
-
- -
- -
- - createNonceFormField('base.optionsUpdate');?> - - - - - -
+
+ +
+ +
+ +
+ Request Processing Options + +
+
Resolve Host Names
+
Controls the resolution of host names (e.g. verizon.com) from visitor's raw IP addresses.
+
+ +
+
+ +
+
Log Requests From Feed Readers
+
Controls the logging of page requests made by Feed Readers. This setting must be enabled in order to compile statistics about your site's feeds.
+
+ +
+
+ +
+
Log Requests From Known Robots
+
Controls the logging of page requests made by known robots and spiders. Turning this feature on will dramatically increase the number of requests that are processed and logged.
+
+ +
+
+ +
+
Log Requests From Named Users
+
Controls the logging of requests made by named users.
+
+ +
+
+ +
+
Excluded IP Addresses
+
Enter a comma seperated list of the IP addresses that you wish to exclude from tracking.
+
+
+ +
+
Anonymize IP Addresses
+
Anonymizes the IP addresses of visitors by removing the last octet from their IP address.
+
+ +
+
+ + + +
+
Fetch Referring Web Page Info
+
Controls whether OWA should crawl the web pages that refer visitors to your web site and extract descriptive meta-data that will be used in reporting.
+
+ +
+
+ +
+
P3P Compact Privacy Policy
+
This setting controls the P3P compact privacy policy that is returned to the browser when OWA sets cookies. Click here for more information on compact privacy policies and choosing the right one for your web site.
+
+
+ +
+
URL Parameters
+
This setting controls the URL parameters that OWA should ignore when processing requests. This is useful for avoiding duplicate URLs due to the use of tracking or others state parameters in your URLs. Parameter names should be separated by comma.
+
+
+ +
+ +
+ +
+ Visitor Announcements + +
+
Announce New Visitors Via E-mail
+
Announces each new visitor to your web site via e-mail. If you have a lot of visitors then you probably want to keep this feature turned off.
+
+ +
+
+ +
+
Notice E-mail Address
+
This is the e-mail address that new visitor e-mails will be sent to.
+
+ +
+ +
+ + +
+ +
+ + Geo-location + +
+
Perform Geo-location Lookup
+
Lookup the geographic location of visitors.
+
+ +
+
+ +
+ +
+ +
+ Feed Tracking + +
+
Feed Link Tracking
+
Adds tracking parameters to RSS or Atom feeds links. This provides a way to track how many visitors come from your feeds.
+
+ +
+
+ +
+ +
+ +
+ Event Queueing + +
+
Event Log File Directory
+
This is the file system path of the file that OWA will write queued events to when Event Queuing mode is turned on. (e.g. /path/to/owa/log/file.txt)
+
+
+ +
+ +
+ + +
+ Object Cache + +
+
Cache Control
+
Enables and disables object caching. This will improve performance under high load conditions. The object cache can be turned on/off via your config file. +
+
+ Status: ONOFF
+
+ +
+
Flush Cache
+
Flushes the object cache
+ +
+ + +
+ +
+ +
+ + Reporting + + +
+
Reporting Timezone
+
This is the timezone that should be used to generate statistics for a specific time period.
+
+ + + +
+
+ +
+ +
+ + createNonceFormField('base.optionsUpdate');?> + + + + + +
\ No newline at end of file diff --git a/modules/base/templates/options_goal_entry.php b/modules/base/templates/options_goal_entry.php index 8407bf6a3..598b424f0 100644 --- a/modules/base/templates/options_goal_entry.php +++ b/modules/base/templates/options_goal_entry.php @@ -1,259 +1,259 @@ -
- -
- -

Goal out($goal_number);?> Settings

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Name: - -
Group: -

- The group that you want to assign this goal to. Goal groups are presented as a tab view on most reports. -

-
- - -

Edit the group label: - - -
Status: - - - -
- Value: -

- The value associated with achieving this goal. -

-
- - Optional -
- Type: -

- The type of goal. -

-
- > URL Destination
- - > Pages / Visit
- - > Visit Duration
- - -
- - -
- -

Goal Details

- - - - - - - - - -
Match Type: - - -
- Goal URL: -

- Example: /register.html -

-
- -
- -

Funnel

- - - - - - - - - -
Step URLNameIs Required?
-
- Add New Funnel Step -
- - -
-

Goal Details

- Not implemented yet. -
- - -
-

Goal Details

- Not implemented yet. -
- - - - - createNonceFormField('base.optionsGoalEdit');?> -
- -
- -
- - - - - - + + + + \ No newline at end of file diff --git a/modules/base/templates/options_goals.tpl b/modules/base/templates/options_goals.tpl index 45d6a2ebc..2532f79dd 100644 --- a/modules/base/templates/options_goals.tpl +++ b/modules/base/templates/options_goals.tpl @@ -1,44 +1,44 @@ -
- -
- - - - - - - - - - - - - - - $goal): ?> - - - - - - - - - - - - - -
Goal NumberGoal NameGoal GroupGoal TypeStatus
Goal out($k);?> Edit

out($goal['goal_name']);?> - out($goal_groups[$goal['goal_group']] ); - } else { - $this->out( $goal['goal_group'] ); - } - } - ?> - out($goal['goal_type']);?>out($goal['goal_status']);?>
- +
+ +
+ + + + + + + + + + + + + + + $goal): ?> + + + + + + + + + + + + + +
Goal NumberGoal NameGoal GroupGoal TypeStatus
Goal out($k);?> Edit

out($goal['goal_name']);?> + out($goal_groups[$goal['goal_group']] ); + } else { + $this->out( $goal['goal_group'] ); + } + } + ?> + out($goal['goal_type']);?>out($goal['goal_status']);?>
+
\ No newline at end of file diff --git a/modules/base/templates/options_modules.tpl b/modules/base/templates/options_modules.tpl index 0d4f901de..e1e83d252 100644 --- a/modules/base/templates/options_modules.tpl +++ b/modules/base/templates/options_modules.tpl @@ -1,49 +1,49 @@ -
-
- - - - - - - - - - - - - - - $v): ?> - - - - - - - - - - - -
ModuleCurrent SchemaRequired SchemaSchema Up to Date?
-
- -
- - - Deactivate - - Activate - - - -
- - - -There are no additional modules installed. - - - +
+
+ + + + + + + + + + + + + + + $v): ?> + + + + + + + + + + + +
ModuleCurrent SchemaRequired SchemaSchema Up to Date?
+
+ +
+ + + Deactivate + + Activate + + + +
+ + + +There are no additional modules installed. + + +
\ No newline at end of file diff --git a/modules/base/templates/options_reporting.tpl b/modules/base/templates/options_reporting.tpl index d8fad3b48..a37ddb8f6 100644 --- a/modules/base/templates/options_reporting.tpl +++ b/modules/base/templates/options_reporting.tpl @@ -2,17 +2,17 @@
-
- Reporting - -
- - Reporting Wrapper:
- -
+
+ Reporting + +
+ + Reporting Wrapper:
+ +
-
- - - +
+ + +
\ No newline at end of file diff --git a/modules/base/templates/options_request_processing.tpl b/modules/base/templates/options_request_processing.tpl index 6a0d52543..f28ef9e0a 100644 --- a/modules/base/templates/options_request_processing.tpl +++ b/modules/base/templates/options_request_processing.tpl @@ -3,97 +3,97 @@
- Request Processing Options - -
- Resolve Host Names: - -
- -
- Log Requests from Feed Readers: - -
- -
- Log Requests from Known Robots: - -
- -
- Announce New Visitors via E-mail: - -
- -
- - Notice Email Address:
- -
- + Request Processing Options + +
+ Resolve Host Names: + +
+ +
+ Log Requests from Feed Readers: + +
+ +
+ Log Requests from Known Robots: + +
+ +
+ Announce New Visitors via E-mail: + +
+ +
+ + Notice Email Address:
+ +
+
- Geo-location Options - -
- - Perform Geo-location Lookup: - -
-
- Geolocation Service: - - -
+ Geo-location Options + +
+ + Perform Geo-location Lookup: + +
+
+ Geolocation Service: + + +
-
- - - + + + +
\ No newline at end of file diff --git a/modules/base/templates/report.tpl b/modules/base/templates/report.tpl index 6462be3a2..0a95b6cdd 100644 --- a/modules/base/templates/report.tpl +++ b/modules/base/templates/report.tpl @@ -1,59 +1,59 @@ - - -
- - - - - get( 'hideReportingNavigation' ) ):?> - - - - -
-
-
- makeNavigationMenu($top_level_report_nav, $currentSiteId);?> -
-
-
- - get( 'hideSitesFilter' ) ):?> -
- -
- -
-
-
-
get('titleSuffix');?>
- -
- - -
-
-
- + + +
+ + + + + get( 'hideReportingNavigation' ) ):?> + + + + +
+
+
+ makeNavigationMenu($top_level_report_nav, $currentSiteId);?> +
+
+
+ + get( 'hideSitesFilter' ) ):?> +
+ +
+ +
+
+
+
get('titleSuffix');?>
+ +
+ + +
+
+
+ diff --git a/modules/base/templates/report_actionDetail.php b/modules/base/templates/report_actionDetail.php index fc58e4c48..f585f15fc 100644 --- a/modules/base/templates/report_actionDetail.php +++ b/modules/base/templates/report_actionDetail.php @@ -1,86 +1,86 @@ -
Action Metrics
-
- - - - - - -
- aggregates as $row):?> -
-

-

-
- -
-
- -
Analysis Workbook
-
- - - -
- - -
- -
- -
- -
- -
- -
- - - +
Action Metrics
+
+ + + + + + +
+ aggregates as $row):?> +
+

+

+
+ +
+
+ +
Analysis Workbook
+
+ + + +
+ + +
+ +
+ +
+ +
+ +
+ +
+ + + diff --git a/modules/base/templates/report_actionTracking.php b/modules/base/templates/report_actionTracking.php index fef60ccbe..0b508d2bc 100644 --- a/modules/base/templates/report_actionTracking.php +++ b/modules/base/templates/report_actionTracking.php @@ -1,50 +1,50 @@ - - - - - - - - - -
-
-
Actions by Name
-
- -
-
-
-
Actions By Group
-
- -
-
- + + + + + + + + + +
+
+
Actions by Name
+
+ +
+
+
+
Actions By Group
+
+ +
+
+ diff --git a/modules/base/templates/report_anchortext.tpl b/modules/base/templates/report_anchortext.tpl index c0e2c2c21..591df6772 100644 --- a/modules/base/templates/report_anchortext.tpl +++ b/modules/base/templates/report_anchortext.tpl @@ -1,63 +1,63 @@ -
-
-

-
-
- - -
- -
-
Top Inbound Link Text
-
- - - -
- - +
+
+

+
+
+ + +
+ +
+
Top Inbound Link Text
+
+ + + +
+ + diff --git a/modules/base/templates/report_commerce.php b/modules/base/templates/report_commerce.php index d2dfe93bc..2495093ce 100644 --- a/modules/base/templates/report_commerce.php +++ b/modules/base/templates/report_commerce.php @@ -1,111 +1,111 @@ -
-
-
-
-
- -
-
- - - - - - - -
- -
- - -
-
Products
- -
- -
- -
- -
-
Traffic Sources
-
- -
- -
- - - - - - - +
+
+
+
+
+ +
+
+ + + + + + + +
+ +
+ + +
+
Products
+ +
+ +
+ +
+ +
+
Traffic Sources
+
+ +
+ +
+ + + + + + + diff --git a/modules/base/templates/report_content.tpl b/modules/base/templates/report_content.tpl index c3ac4b9b0..1ac4f29a7 100644 --- a/modules/base/templates/report_content.tpl +++ b/modules/base/templates/report_content.tpl @@ -1,121 +1,121 @@ -
-
-
-
-
- -
-
- - - - - - - -
- -
- - -
-
Top Pages
- -
- -
- -
-
Content Reports
-
-
    -
  • - Domstream Recordings - See user mouse movement and keypress recordings. -
  • -
  • - Actions - See which actions your user performed. -
  • -
  • - Entry & Exits - See which web pages user entered and exited on. -
  • -
  • - Feeds - See trends for feed subscribers and usage. -
  • -
-
- - -
-
Top Page Types
-
- -
- -
- - - - - - - +
+
+
+
+
+ +
+
+ + + + + + + +
+ +
+ + +
+
Top Pages
+ +
+ +
+ +
+
Content Reports
+
+
    +
  • + Domstream Recordings - See user mouse movement and keypress recordings. +
  • +
  • + Actions - See which actions your user performed. +
  • +
  • + Entry & Exits - See which web pages user entered and exited on. +
  • +
  • + Feeds - See trends for feed subscribers and usage. +
  • +
+
+ + +
+
Top Page Types
+
+ +
+ +
+ + + + + + + diff --git a/modules/base/templates/report_dashboard.tpl b/modules/base/templates/report_dashboard.tpl index c1c9b1a94..bba98021f 100644 --- a/modules/base/templates/report_dashboard.tpl +++ b/modules/base/templates/report_dashboard.tpl @@ -1,204 +1,204 @@ -
-
Site Metrics
- -

-
- -
-
- - - - - -
- -
-
Top Content
- -
- -
- -
-
Visitor Types
-
-
- -
-
Latest Visits
- -
- -
- - getDataRows()):?> -
-
Actions
- -
- - - - - - -
- getDataRows() as $k => $row):?> -
-

-

-
- -
- - - -
-
- - -
-
Traffic Sources
-
-
- -
-
Top Referrers
- -
- -
-
- -
-
OWA News
- getWidget('base.widgetOwaNews','',false);?> -
-
- - - +
+
Site Metrics
+ +

+
+ +
+
+ + + + + +
+ +
+
Top Content
+ +
+ +
+ +
+
Visitor Types
+
+
+ +
+
Latest Visits
+ +
+ +
+ + getDataRows()):?> +
+
Actions
+ +
+ + + + + + +
+ getDataRows() as $k => $row):?> +
+

+

+
+ +
+ + + +
+
+ + +
+
Traffic Sources
+
+
+ +
+
Top Referrers
+ +
+ +
+
+ +
+
OWA News
+ getWidget('base.widgetOwaNews','',false);?> +
+
+ + + \ No newline at end of file diff --git a/modules/base/templates/report_dimensionDetail.php b/modules/base/templates/report_dimensionDetail.php index 97a2c9710..f058c9afe 100644 --- a/modules/base/templates/report_dimensionDetail.php +++ b/modules/base/templates/report_dimensionDetail.php @@ -1,64 +1,64 @@
- renderDimension($dimension_template, $dimension_properties);?> + renderDimension($dimension_template, $dimension_properties);?>
- -
-
-
- - $tab): ?> -
- -
- -
- -
- get('hideGrid')):?> -
- - -
- -
-
- - + +
+
+
+ + $tab): ?> +
+ +
+ +
+ +
+ get('hideGrid')):?> +
+ + +
+ +
+
+ + \ No newline at end of file diff --git a/modules/base/templates/report_dimensionDetailNoTabs.php b/modules/base/templates/report_dimensionDetailNoTabs.php index ec2c9582f..9e617025a 100644 --- a/modules/base/templates/report_dimensionDetailNoTabs.php +++ b/modules/base/templates/report_dimensionDetailNoTabs.php @@ -1,109 +1,109 @@
- renderDimension($dimension_template, $dimension_properties);?> + renderDimension($dimension_template, $dimension_properties);?>
- -
-
-
- - -
- - - -
- + +
+
+
+ + +
+ + + +
+
get( 'dimensions' ) ):?>
- -
- - + +
+ +
diff --git a/modules/base/templates/report_dimensionalTrend.php b/modules/base/templates/report_dimensionalTrend.php index 5ecbfc249..2a08cd378 100644 --- a/modules/base/templates/report_dimensionalTrend.php +++ b/modules/base/templates/report_dimensionalTrend.php @@ -1,109 +1,109 @@
- -
-
-
- - $tab): ?> -
- -
- get('pie' ) ): ?> -
- -
- get('hideGrid')):?> -
- - -
- -
+ +
+
+
+ + $tab): ?> +
+ +
+ get('pie' ) ): ?> +
+ +
+ get('hideGrid')):?> +
+ + +
+ +
\ No newline at end of file diff --git a/modules/base/templates/report_document.tpl b/modules/base/templates/report_document.tpl index 0c11e19be..45dccaf72 100644 --- a/modules/base/templates/report_document.tpl +++ b/modules/base/templates/report_document.tpl @@ -1,79 +1,79 @@ - -
- renderDimension($dimension_template, $dimension_properties);?> -
- - - - -
- - - - -
- -
- -
- -
-
Prior Pages Viewed
-
-
- -
-
Related Reports:
- -

- Heatmap Overlay (Firefox 3.5+ required) -

- -

- Domstreams - mouse movement recordings. -

- -

- Dom Clicks - analysis of dom clicks. -

-
-
-
Next Pages Viewed
-
- -
-
- - - - - + +
+ renderDimension($dimension_template, $dimension_properties);?> +
+ + + + +
+ + + + +
+ +
+ +
+ +
+
Prior Pages Viewed
+
+
+ +
+
Related Reports:
+ +

+ Heatmap Overlay (Firefox 3.5+ required) +

+ +

+ Domstreams - mouse movement recordings. +

+ +

+ Dom Clicks - analysis of dom clicks. +

+
+
+
Next Pages Viewed
+
+ +
+
+ + + + + \ No newline at end of file diff --git a/modules/base/templates/report_document_detail.tpl b/modules/base/templates/report_document_detail.tpl index 34088f62a..a2b69bb5d 100644 --- a/modules/base/templates/report_document_detail.tpl +++ b/modules/base/templates/report_document_detail.tpl @@ -1,14 +1,14 @@ - - - - - - - - - - - - - -
Title
URL:
Page Type:
+ + + + + + + + + + + + + +
Title
URL:
Page Type:
diff --git a/modules/base/templates/report_dom_clicks.php b/modules/base/templates/report_dom_clicks.php index 00a918b2a..95e4645b6 100644 --- a/modules/base/templates/report_dom_clicks.php +++ b/modules/base/templates/report_dom_clicks.php @@ -1,90 +1,90 @@ - +
- - - - - - - -
- -
-
Dom IDs
-
- -
- -
-
Name Attributes
-
- -
- -
- -
-
HTML Tags
-
- -
- -
-
Dom Classes
-
- -
- -
+ + + + + + + +
+ +
+
Dom IDs
+
+ +
+ +
+
Name Attributes
+
+ +
+ +
+ +
+
HTML Tags
+
+ +
+ +
+
Dom Classes
+
+ +
+ +
\ No newline at end of file diff --git a/modules/base/templates/report_domstreams.tpl b/modules/base/templates/report_domstreams.tpl index 8accf5a80..f56afda58 100644 --- a/modules/base/templates/report_domstreams.tpl +++ b/modules/base/templates/report_domstreams.tpl @@ -1,52 +1,52 @@ - - - - - - - - - - - - - - - rows as $ds): ?> - - - - - - - - - - -
getLabel('timestamp');?>getLabel('page_url');?>getLabel('duration');?>
- - - - truncate($ds['page_url'], 150);?> - - - - - Play -
- -makePaginationFromResultSet($domstreams, array('do' => 'base.reportDomstreams'), true);?> - - - There are no refering web pages for this time period. + + + + + + + + + + + + + + + rows as $ds): ?> + + + + + + + + + + +
getLabel('timestamp');?>getLabel('page_url');?>getLabel('duration');?>
+ + + + truncate($ds['page_url'], 150);?> + + + + + Play +
+ +makePaginationFromResultSet($domstreams, array('do' => 'base.reportDomstreams'), true);?> + + + There are no refering web pages for this time period. \ No newline at end of file diff --git a/modules/base/templates/report_ecommerce.php b/modules/base/templates/report_ecommerce.php index a194ba13c..e105d3a0b 100644 --- a/modules/base/templates/report_ecommerce.php +++ b/modules/base/templates/report_ecommerce.php @@ -1,106 +1,106 @@ -
- -
- - -
-
-
- - -
- - - - - - - -
-
-
Product Performance
-
- -
- -
-
Sales Sources
-
- -
-
-
-
Related Reports
-
- -
-
-
- - - +
+ +
+ + +
+
+
+ + +
+ + + + + + + +
+
+
Product Performance
+
+ +
+ +
+
Sales Sources
+
+ +
+
+
+
Related Reports
+
+ +
+
+
+ + + diff --git a/modules/base/templates/report_geolocation.tpl b/modules/base/templates/report_geolocation.tpl index 43eebf887..5d02593f3 100644 --- a/modules/base/templates/report_geolocation.tpl +++ b/modules/base/templates/report_geolocation.tpl @@ -1,17 +1,17 @@ - - - -
-

Download KML

- - -
- -makePaginationFromResultSet($latest_visits, array('do' => 'base.reportVisitsGeolocation'));?> - - - + + + +
+

Download KML

+ + +
+ +makePaginationFromResultSet($latest_visits, array('do' => 'base.reportVisitsGeolocation'));?> + + + diff --git a/modules/base/templates/report_goal_funnel.php b/modules/base/templates/report_goal_funnel.php index 54049de1e..000d00f71 100644 --- a/modules/base/templates/report_goal_funnel.php +++ b/modules/base/templates/report_goal_funnel.php @@ -1,133 +1,133 @@
- - Choose a goal: + + Choose a goal:
get('funnel') ):?> - - - - - - $step):?> - - - - - - - - - - - - - + + + + + + $step):?> + + + + + + + + + + + + +
Prior Page Viewed

out($goal_conversion_rate);?> conversion rate

Next Page Viewed
-
- -
-
-
Step out($step['step_number']);?>: out($step['name']);?>
-
out($step['visitors']);?> visitors
-
out($step['url']);?>
-
- -
-
-
-
- out($funnel[$k+1]['visitor_percentage']);?>
- Proceeded to step: out($funnel[$k+1]['name']); ?> -
Prior Page Viewed

out($goal_conversion_rate);?> conversion rate

Next Page Viewed
+
+ +
+
+
Step out($step['step_number']);?>: out($step['name']);?>
+
out($step['visitors']);?> visitors
+
out($step['url']);?>
+
+ +
+
+
+
+ out($funnel[$k+1]['visitor_percentage']);?>
+ Proceeded to step: out($funnel[$k+1]['name']); ?> +
@@ -142,10 +142,10 @@ // Bind event handlers jQuery(document).ready(function(){ - jQuery('#goalChooser').change(function() { - var num = jQuery("#goalChooser option:selected").val(); - OWA.items['base-reportGoalFunnel'].setRequestProperty('goalNumber', num); - OWA.items['base-reportGoalFunnel'].reload(); - }); + jQuery('#goalChooser').change(function() { + var num = jQuery("#goalChooser option:selected").val(); + OWA.items['base-reportGoalFunnel'].setRequestProperty('goalNumber', num); + OWA.items['base-reportGoalFunnel'].reload(); + }); }); \ No newline at end of file diff --git a/modules/base/templates/report_goals.php b/modules/base/templates/report_goals.php index 33c4b483a..b2da5781d 100644 --- a/modules/base/templates/report_goals.php +++ b/modules/base/templates/report_goals.php @@ -1,73 +1,73 @@ -
- -
- - -
-
-
- - -
- - - - - - - -
-
-
Goal Performance
-
- - - -
- -
-
-
Related Reports
-
- -
-
-
- - - +
+ +
+ + +
+
+
+ + +
+ + + + + + + +
+
+
Goal Performance
+
+ + + +
+ +
+
+
Related Reports
+
+ +
+
+
+ + + diff --git a/modules/base/templates/report_header.tpl b/modules/base/templates/report_header.tpl index ac6fbd74d..56ac833d7 100644 --- a/modules/base/templates/report_header.tpl +++ b/modules/base/templates/report_header.tpl @@ -1,8 +1,7 @@ - - - - - - -
- \ No newline at end of file + + + + + + +
diff --git a/modules/base/templates/report_latest_visits.tpl b/modules/base/templates/report_latest_visits.tpl index ba1810d33..54363662b 100644 --- a/modules/base/templates/report_latest_visits.tpl +++ b/modules/base/templates/report_latest_visits.tpl @@ -1,12 +1,12 @@ - - - resultsRows as $row): ?> - - - - -
- makePaginationFromResultSet($visits);?> - - There were no visits during this time period. + + + resultsRows as $row): ?> + + + + +
+ makePaginationFromResultSet($visits);?> + + There were no visits during this time period. \ No newline at end of file diff --git a/modules/base/templates/report_nav.tpl b/modules/base/templates/report_nav.tpl index f529957c4..ba82d544b 100644 --- a/modules/base/templates/report_nav.tpl +++ b/modules/base/templates/report_nav.tpl @@ -1,39 +1,39 @@ -
- -
    - $l): ?> - getCurrentUser()->isCapable($l['priviledge'], $currentSiteId)) { continue; } ?> -
  • -
    - -
    -
    -
    - -
    - -
    - - - -
    -
      - - getCurrentUser()->isCapable($sgl['priviledge'], $currentSiteId)) continue; ?> -
    • -
      - -
      - -
    • - -
    -
    - -
    -
  • - -
- -
- +
+ +
    + $l): ?> + getCurrentUser()->isCapable($l['priviledge'], $currentSiteId)) { continue; } ?> +
  • +
    + +
    +
    +
    + +
    + +
    + + + +
    +
      + + getCurrentUser()->isCapable($sgl['priviledge'], $currentSiteId)) continue; ?> +
    • +
      + +
      + +
    • + +
    +
    + +
    +
  • + +
+ +
+ diff --git a/modules/base/templates/report_period_filters.tpl b/modules/base/templates/report_period_filters.tpl index c601339e9..75c11278c 100644 --- a/modules/base/templates/report_period_filters.tpl +++ b/modules/base/templates/report_period_filters.tpl @@ -1,362 +1,362 @@ - - - - - - - - - - - - - - - - - -
SiteReporting Period
-
- -
-
- - - - - - - - - - - - -
- CHECKED> - Time Period:
- -
-
- CHECKED> - Date Period: -
- -
-
- -
- -
- - - - - - - - - - - - - - -
MonthDayYear
- - - - - - -
-
- -
- - - - - - - - - - - - -
MonthYear
- - - -
-
- -
- - - - - - - - - - -
Year
- -
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Start MonthStart DayStart YearEnd MonthEnd DayEnd Year
- - - - - - - to - - - - - - -
-
- -
- - - + + + + + + + + + + + + + + + + + +
SiteReporting Period
+
+ +
+
+ + + + + + + + + + + + +
+ CHECKED> + Time Period:
+ +
+
+ CHECKED> + Date Period: +
+ +
+
+ +
+ +
+ + + + + + + + + + + + + + +
MonthDayYear
+ + + + + + +
+
+ +
+ + + + + + + + + + + + +
MonthYear
+ + + +
+
+ +
+ + + + + + + + + + +
Year
+ +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Start MonthStart DayStart YearEnd MonthEnd DayEnd Year
+ + + + + + + to + + + + + + +
+
+ +
+ + + diff --git a/modules/base/templates/report_top_visitors.tpl b/modules/base/templates/report_top_visitors.tpl index b981df05f..d4c7f2501 100644 --- a/modules/base/templates/report_top_visitors.tpl +++ b/modules/base/templates/report_top_visitors.tpl @@ -1,36 +1,36 @@ - - - - - - - - - - - - - - - - - -
VisitorVisits
- - - - - - - - - - - - - -
- - -There are no visitors for this time period. + + + + + + + + + + + + + + + + + +
VisitorVisits
+ + + + + + + + + + + + + +
+ + +There are no visitors for this time period. \ No newline at end of file diff --git a/modules/base/templates/report_traffic.tpl b/modules/base/templates/report_traffic.tpl index ca3ca20c9..bddf69f60 100644 --- a/modules/base/templates/report_traffic.tpl +++ b/modules/base/templates/report_traffic.tpl @@ -1,211 +1,211 @@ -
-
-
-
-
- - - - - - - - -
-
-
-
-
-
- - - - - - - -
- -
- -
-
Top Sources
- -
- -
- -
-
Top Keywords
- -
- -
- -
- -
-
Top Referrals
-
- -
- -
Related Reports
-
-
    -
  • - Search Engines - See which search engines your visitors are coming from. -
  • -
  • - Keywords - See what keywords your visitor are using to find your web site. -
  • -
  • - Referring Web Sites - See which web sites are linking to your web site. -
  • -
  • - Inbound Link Text - See what words Referring Web Sites use to describe your web site. -
  • -
-
- - -
- - - - - - - - - + + + + \ No newline at end of file diff --git a/modules/base/templates/report_transaction_detail.php b/modules/base/templates/report_transaction_detail.php index ce3480508..589d410d3 100644 --- a/modules/base/templates/report_transaction_detail.php +++ b/modules/base/templates/report_transaction_detail.php @@ -1,82 +1,82 @@ - - - - - - array( - 'label' => 'Order Id' - ), - 'order_source' => array( - 'label' => 'Order Source' - ), - 'gateway' => array( - 'label' => 'Transaction Processing Gateway' - ), - 'total_revenue' => array( - 'label' => 'Total Revenue', - 'data_type' => 'currency' - ), - 'tax_revenue' => array( - 'label' => 'Tax Revenue' - ), - 'shipping_revenue' => array( - 'label' => 'Shipping Revenue' - ), - - ); - ?> - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + array( + 'label' => 'Order Id' + ), + 'order_source' => array( + 'label' => 'Order Source' + ), + 'gateway' => array( + 'label' => 'Transaction Processing Gateway' + ), + 'total_revenue' => array( + 'label' => 'Total Revenue', + 'data_type' => 'currency' + ), + 'tax_revenue' => array( + 'label' => 'Tax Revenue' + ), + 'shipping_revenue' => array( + 'label' => 'Shipping Revenue' + ), + + ); + ?> + + + + + + + + + + + + + + + + + + + + + + + + + +
Order Idout( $trans_detail['order_id'] );?>
Order Sourceout( $trans_detail['order_source'] );?>
Processing Gatewayout( $trans_detail['gateway'] );?>
Total Revenueout( $this->formatCurrency( $trans_detail['total_revenue'] ) );?>
Tax Revenueout( $this->formatCurrency( $trans_detail['tax_revenue'] ) );?>
Shipping Revenueout( $this->formatCurrency( $trans_detail['shipping_revenue'] ) );?>
Order Idout( $trans_detail['order_id'] );?>
Order Sourceout( $trans_detail['order_source'] );?>
Processing Gatewayout( $trans_detail['gateway'] );?>
Total Revenueout( $this->formatCurrency( $trans_detail['total_revenue'] ) );?>
Tax Revenueout( $this->formatCurrency( $trans_detail['tax_revenue'] ) );?>
Shipping Revenueout( $this->formatCurrency( $trans_detail['shipping_revenue'] ) );?>

Transaction Line Items

- - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + +
Product NameSKUUnit PriceQuantityItem Revenue
out( $li['product_name'] ); ?> (out( $li['category'] ); ?>)out( $li['sku'] ); ?>out( $this->formatCurrency( $li['unit_price'] ) ); ?>out( $li['quantity'] ); ?>out( $this->formatCurrency( $li['item_revenue'] ) ); ?>
Product NameSKUUnit PriceQuantityItem Revenue
out( $li['product_name'] ); ?> (out( $li['category'] ); ?>)out( $li['sku'] ); ?>out( $this->formatCurrency( $li['unit_price'] ) ); ?>out( $li['quantity'] ); ?>out( $this->formatCurrency( $li['item_revenue'] ) ); ?>
None. diff --git a/modules/base/templates/report_transactions.php b/modules/base/templates/report_transactions.php index 2fec1c461..38cfab866 100644 --- a/modules/base/templates/report_transactions.php +++ b/modules/base/templates/report_transactions.php @@ -1,71 +1,71 @@ -
-
-
-
-
- -
-
- - - - - - - -
- -
-
Transaction Roster
-
- -
- -
- - - - - - - +
+
+
+
+
+ +
+
+ + + + + + + +
+ +
+
Transaction Roster
+
+ +
+ +
+ + + + + + + diff --git a/modules/base/templates/report_trend_section.php b/modules/base/templates/report_trend_section.php index 81496644e..7545b8f93 100644 --- a/modules/base/templates/report_trend_section.php +++ b/modules/base/templates/report_trend_section.php @@ -1,31 +1,31 @@
- -
- -
-
-
- +
+ + +
+
+
+
\ No newline at end of file diff --git a/modules/base/templates/report_visit.tpl b/modules/base/templates/report_visit.tpl index e76d61b9e..f73b2b81f 100644 --- a/modules/base/templates/report_visit.tpl +++ b/modules/base/templates/report_visit.tpl @@ -1,21 +1,21 @@ -
Visit Summary
-
- -
- -
Visit Clickstream
- -
- -
- resultsRows as $s): ?> -
::
-
- -
-

- -
- -
+
Visit Summary
+
+ +
+ +
Visit Clickstream
+ +
+ +
+ resultsRows as $s): ?> +
::
+
+ +
+

+ +
+ +
\ No newline at end of file diff --git a/modules/base/templates/report_visit_summary.tpl b/modules/base/templates/report_visit_summary.tpl index c5d9d86a5..d65ff33c9 100644 --- a/modules/base/templates/report_visit_summary.tpl +++ b/modules/base/templates/report_visit_summary.tpl @@ -1,88 +1,88 @@ -
- - - - - - - -
- / @ at : | - , choose_browser_icon($visit['ua_browser_type']);?>
- - - - - - - - - - - - - - - - - - - - - - - - - -
- - - New Visitor - - Repeat Visitor - - - - - - - - - - (Last visit was - - day ago. - - days ago. - - ) - - -
- Entry Page - - ()
-
- - Refering URL - - truncate($visit['referer_page_title'], 80, '...');?>
truncate($visit['referer_url'], 80, '...');?>truncate($visit['referer_url'], 50, '...');?> -
- -
- -
- -
- -
- Pages -
-
- -
-
-
- - -
- +
+ + + + + + + +
+ / @ at : | - , choose_browser_icon($visit['ua_browser_type']);?>
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + New Visitor + + Repeat Visitor + + + + + + + + + - (Last visit was + + day ago. + + days ago. + + ) + + +
+ Entry Page + + ()
+
+ + Refering URL + + truncate($visit['referer_page_title'], 80, '...');?>
truncate($visit['referer_url'], 80, '...');?>truncate($visit['referer_url'], 50, '...');?> +
+ +
+ +
+ +
+ +
+ Pages +
+
+ +
+
+
+ + +
+
\ No newline at end of file diff --git a/modules/base/templates/report_visit_summary_balloon.tpl b/modules/base/templates/report_visit_summary_balloon.tpl index bfebeaeab..6ac5d801c 100644 --- a/modules/base/templates/report_visit_summary_balloon.tpl +++ b/modules/base/templates/report_visit_summary_balloon.tpl @@ -1,58 +1,58 @@ -

-

- - -New Visitor - -Returning Visitor (Last visit was - -day ago. - -days ago. - -) - -choose_browser_icon($visit['ua_browser_type']);?>

- - - / at : -

- - -, - -

- - - - - - - - - - - - - - - -
- Visitor - - - - -
- Entry Page - - escapeForXml($visit['document_page_title']);?> ()
- -
- Refering URL - - escapeForXml($this->truncate($visit['referer_page_title'], 80, '...'));?> truncate($visit['referer_url'], 35, '...');?>truncate($visit['referer_url'], 50, '...');?> -
- -

View Visit Details

- +

+

+ + +New Visitor + +Returning Visitor (Last visit was + +day ago. + +days ago. + +) + +choose_browser_icon($visit['ua_browser_type']);?>

+ + - / at : +

+ + +, + +

+ + + + + + + + + + + + + + + +
+ Visitor + + + + +
+ Entry Page + + escapeForXml($visit['document_page_title']);?> ()
+ +
+ Refering URL + + escapeForXml($this->truncate($visit['referer_page_title'], 80, '...'));?> truncate($visit['referer_url'], 35, '...');?>truncate($visit['referer_url'], 50, '...');?> +
+ +

View Visit Details

+
\ No newline at end of file diff --git a/modules/base/templates/report_visitor.tpl b/modules/base/templates/report_visitor.tpl index 57359ba50..6cc81c749 100644 --- a/modules/base/templates/report_visitor.tpl +++ b/modules/base/templates/report_visitor.tpl @@ -1,40 +1,40 @@ -
-
- - out( $visitor_label );?> -
-
-
- renderKpiInfobox( $first_visit_date, 'First Visit' ); ?> - -
-
- -
- - - - - - - -
-
-
Latest Visits
- - makePaginationFromResultSet($visits, array('do' => 'base.reportVisitors'), true);?> -
-
-
-
Latest Actions
- - getLatestActions($this->get('startDate'), - $this->get('endDate'), - $this->get('siteId'), - $this->get('visitor_id'), - '', - '300px'); ?> -
-
- - +
+
+ + out( $visitor_label );?> +
+
+
+ renderKpiInfobox( $first_visit_date, 'First Visit' ); ?> + +
+
+ +
+ + + + + + + +
+
+
Latest Visits
+ + makePaginationFromResultSet($visits, array('do' => 'base.reportVisitors'), true);?> +
+
+
+
Latest Actions
+ + getLatestActions($this->get('startDate'), + $this->get('endDate'), + $this->get('siteId'), + $this->get('visitor_id'), + '', + '300px'); ?> +
+
+ + diff --git a/modules/base/templates/report_visitors.tpl b/modules/base/templates/report_visitors.tpl index 22effe30a..1abfcaae1 100644 --- a/modules/base/templates/report_visitors.tpl +++ b/modules/base/templates/report_visitors.tpl @@ -1,103 +1,103 @@ -
-
-
- - -
-
- -
- - - - - - - -
-
-
Latest Visits
- - makePaginationFromResultSet($visits, array('do' => 'base.reportVisitors'), true);?> -
-
-
-
Visitor Reports
-

- Visitor Loyalty - See how long ago your visitors first came to your web site. -

-

- Geo-location - See which parts of the world your visitors are coming from. -

-

- Domains - See which Networks or Internet hosts your visitors are coming from. -

-
- - -
-
Browser Types
-
- -
- -
-
Most Frequent Visitors
-
- -
- -
- - - - +
+
+ +
+ + + + + + + +
+
+
Latest Visits
+ + makePaginationFromResultSet($visits, array('do' => 'base.reportVisitors'), true);?> +
+
+
+
Visitor Reports
+

+ Visitor Loyalty - See how long ago your visitors first came to your web site. +

+

+ Geo-location - See which parts of the world your visitors are coming from. +

+

+ Domains - See which Networks or Internet hosts your visitors are coming from. +

+
+ + +
+
Browser Types
+
+ +
+ +
+
Most Frequent Visitors
+
+ +
+ +
+ + + + \ No newline at end of file diff --git a/modules/base/templates/report_visitors_roster.tpl b/modules/base/templates/report_visitors_roster.tpl index a82f59e7c..f5181d53b 100644 --- a/modules/base/templates/report_visitors_roster.tpl +++ b/modules/base/templates/report_visitors_roster.tpl @@ -1,27 +1,27 @@ -

:

- - - - - - - - - - - - - +

:

+ +
- - - -
- There are no visitors during this time period. -
+ + + + + + + + + + +
+ + + +
+ There are no visitors during this time period. +
\ No newline at end of file diff --git a/modules/base/templates/report_visits.php b/modules/base/templates/report_visits.php index 43325b9b5..f2a5e298b 100644 --- a/modules/base/templates/report_visits.php +++ b/modules/base/templates/report_visits.php @@ -1,5 +1,5 @@ -
-
Latest Visits
- - makePagination($pagination, array('do' => $params['do']));?> +
+
Latest Visits
+ + makePagination($pagination, array('do' => $params['do']));?>
\ No newline at end of file diff --git a/modules/base/templates/resultSetHtml.php b/modules/base/templates/resultSetHtml.php index e7741de5b..b44b581e5 100644 --- a/modules/base/templates/resultSetHtml.php +++ b/modules/base/templates/resultSetHtml.php @@ -1,35 +1,35 @@ - - - + + + resultsRows):?> resultsRows[0] as $k => $v):?> - + - - + + - - - - - + + + + + resultsRows):?> resultsRows as $row):?> - + $v):?> - + - + - +
- - - - - - + + + + + +
diff --git a/modules/base/templates/resultSetXml.php b/modules/base/templates/resultSetXml.php index 327ed7bf2..aa815c8c5 100644 --- a/modules/base/templates/resultSetXml.php +++ b/modules/base/templates/resultSetXml.php @@ -1,31 +1,31 @@ ");?> - + timePeriod as $k => $v):?> - %s\n", $k, $this->escapeForXml($v), $k);?> + %s\n", $k, $this->escapeForXml($v), $k);?> - + - + aggregates as $item):?> - \n", $item['result_type'], $this->escapeForXml($item['name']), $this->escapeForXml($item['value']), $this->escapeForXml($item['label']));?> + \n", $item['result_type'], $this->escapeForXml($item['name']), $this->escapeForXml($item['value']), $this->escapeForXml($item['label']));?> - + - resultsTotal;?> - - resultsReturned;?> - - resultsPerPage;?> - - + resultsTotal;?> + + resultsReturned;?> + + resultsPerPage;?> + + resultsRows as $row):?> - + - \n", $item['result_type'], $this->escapeForXml($item['name']), $this->escapeForXml($item['value']), $this->escapeForXml($item['label']));?> + \n", $item['result_type'], $this->escapeForXml($item['name']), $this->escapeForXml($item['value']), $this->escapeForXml($item['label']));?> - + - + \ No newline at end of file diff --git a/modules/base/templates/row_action.php b/modules/base/templates/row_action.php index 53566fbde..0b9c6a31a 100644 --- a/modules/base/templates/row_action.php +++ b/modules/base/templates/row_action.php @@ -1,22 +1,22 @@ -
-
- out( $row['action_group'] ) . ' > ' . $this->out( $row['action_name'] ); - } else { - $this->out( $row['action_name'] ); - } - - ?> - - -
-
- Label: out( $row['action_label'] );?>
-
Value: out( $row['numeric_value'] );?>
-
-
- +
+
+ out( $row['action_group'] ) . ' > ' . $this->out( $row['action_name'] ); + } else { + $this->out( $row['action_name'] ); + } + + ?> + + +
+
+ Label: out( $row['action_label'] );?>
+
Value: out( $row['numeric_value'] );?>
+
+
+ \ No newline at end of file diff --git a/modules/base/templates/row_visitSummary.tpl b/modules/base/templates/row_visitSummary.tpl index 53a52157c..0e7d8e87c 100644 --- a/modules/base/templates/row_visitSummary.tpl +++ b/modules/base/templates/row_visitSummary.tpl @@ -1,101 +1,101 @@ - -
- -

»

- - - - - - - - - -
- - - -
- - - New Visitor
- - -
- - - - isValueSet( $row[ 'session_user_name' ] ) ) { - $this->out( $row[ 'session_user_name' ] ); - } else { - $this->out( $row['visitor_id'] ); - }?> -
- isValueSet( $row['location_city'] ) || $this->isValueSet( $row['location_country'] ) ):?> - , - -
- Visitor Detail » -  Visit Detail » -
-
- - renderKpiInfobox( - $this->choose_browser_icon($row['browser_type']), - 'Browser Type', - $this->makeLink(array('session_id' => $row['session_id'], 'do' => 'base.reportVisit'), true), - 'visitSummaryKpi' - );?> - - - - renderKpiInfobox( - $row['session_num_pageviews'], - 'Pages Viewed', - $this->makeLink(array('session_id' => $row['session_id'], 'do' => 'base.reportVisit'), true), - 'visitSummaryKpi' - );?> - - - renderKpiInfobox( - date("G:i:s",mktime(0,0,($row['session_last_req'] - $row['session_timestamp']))), - 'Visit Length', - '', - 'visitSummaryKpi' - );?> - - - renderKpiInfobox( - $row['session_num_prior_visits'], - 'Prior Visits', - '', - 'visitSummaryKpi' - );?> - -
- - - - - - - - - - - - - - - -
- - - -
- -
- -
+ +
+ +

»

+ + + + + + + + + +
+ + + +
+ + + New Visitor
+ + +
+ + + + isValueSet( $row[ 'session_user_name' ] ) ) { + $this->out( $row[ 'session_user_name' ] ); + } else { + $this->out( $row['visitor_id'] ); + }?> +
+ isValueSet( $row['location_city'] ) || $this->isValueSet( $row['location_country'] ) ):?> + , + +
+ Visitor Detail » +  Visit Detail » +
+
+ + renderKpiInfobox( + $this->choose_browser_icon($row['browser_type']), + 'Browser Type', + $this->makeLink(array('session_id' => $row['session_id'], 'do' => 'base.reportVisit'), true), + 'visitSummaryKpi' + );?> + + + + renderKpiInfobox( + $row['session_num_pageviews'], + 'Pages Viewed', + $this->makeLink(array('session_id' => $row['session_id'], 'do' => 'base.reportVisit'), true), + 'visitSummaryKpi' + );?> + + + renderKpiInfobox( + date("G:i:s",mktime(0,0,($row['session_last_req'] - $row['session_timestamp']))), + 'Visit Length', + '', + 'visitSummaryKpi' + );?> + + + renderKpiInfobox( + $row['session_num_prior_visits'], + 'Prior Visits', + '', + 'visitSummaryKpi' + );?> + +
+ + + + + + + + + + + + + + + +
+ + + +
+ +
+ +
\ No newline at end of file diff --git a/modules/base/templates/sites.tpl b/modules/base/templates/sites.tpl index 4f0756cb9..e6277cc11 100644 --- a/modules/base/templates/sites.tpl +++ b/modules/base/templates/sites.tpl @@ -1,80 +1,80 @@ - -

Below is the list of web sites that are being tracked.

- -getCurrentUser()->isCapable('edit_sites')): ?> -

Add New

- - - - -
- - - - - - - - - - - -
- getSiteThumbnail( $site->get( 'domain' ), 150 );?> - - - out( $site->get('name') );?> -
- get('description') != ''):?> - out( $site->get('description') );?>
- - out( $site->get('domain') );?>

-
- View Reports - getCurrentUser()->isCapable('edit_sites')): ?> - | Edit Profile - | Get Tracking Code - - getCurrentUser()->isCapable('edit_settings')): ?> - Goals - - getCurrentUser()->isCapable('edit_sites')): ?> - | Delete - -
-
- -
- - - - -
-
- - - -There are no tracked sites. -getCurrentUser()->isCapable('edit_sites')): ?> - Add a site. - - - - + +

Below is the list of web sites that are being tracked.

+ +getCurrentUser()->isCapable('edit_sites')): ?> +

Add New

+ + + + +
+ + + + + + + + + + + +
+ getSiteThumbnail( $site->get( 'domain' ), 150 );?> + + + out( $site->get('name') );?> +
+ get('description') != ''):?> + out( $site->get('description') );?>
+ + out( $site->get('domain') );?>

+
+ View Reports + getCurrentUser()->isCapable('edit_sites')): ?> + | Edit Profile + | Get Tracking Code + + getCurrentUser()->isCapable('edit_settings')): ?> + Goals + + getCurrentUser()->isCapable('edit_sites')): ?> + | Delete + +
+
+ +
+ + + + +
+
+ + + +There are no tracked sites. +getCurrentUser()->isCapable('edit_sites')): ?> + Add a site. + + + + diff --git a/modules/base/templates/sites_addoredit.tpl b/modules/base/templates/sites_addoredit.tpl index eef7e775a..a4b3d2dfc 100644 --- a/modules/base/templates/sites_addoredit.tpl +++ b/modules/base/templates/sites_addoredit.tpl @@ -1,128 +1,128 @@ -
out( $headline );?>
-
-
- - Site Profile - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Site ID:out( $site['site_id'] );?>
Domain:out( $site['domain'] );?> - - - -
- out( @$validation_errors['domain'] );?> -
Site Name:
Description: - -
-
- createNonceFormField($action);?> - - - -
- -
- - -
- -
- Site Settings - -
-
P3P Compact Privacy Policy
-
This setting controls the P3P compact privacy policy that is returned to the browser when OWA sets cookies. Click here for more information on compact privacy policies and choosing the right one for your web site.
-
-
- -
-
Domain Aliases
-
This setting allows you to specify additional domain names that you want OWA to treat as the same as the one you are using for this tracked website. For example, if the domain of your website is "www.mydomain.com" you could add an alias here for "mydomain.com". Aliases should be separated by comma.
-
-
- - -
-
URL Parameters
-
This setting controls the URL parameters that OWA should ignore when processing requests. This is useful for avoiding duplicate URLs due to the use of tracking or others state parameters in your URLs. Parameter names should be separated by comma.
-
-
- -
-
Default Page
-
This is the page that your web server defaults to when there is no page specified in your URL (e.g. index.html). Use this setting to combine page views for www.domain.com and www.domain.com/index.html.
-
-
- -
-
e-commerce Reporting
-
Adds e-commerce metrics/statistics to reports.
-
- -
-
- -
- - createNonceFormField('base.sitesEditSettings');?> - - - - -
-
-
-
- Allowed Users - - -
- createNonceFormField('base.sitesEditAllowedUsers');?> - - - - -
- -
-
+
out( $headline );?>
+
+
+ + Site Profile + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Site ID:out( $site['site_id'] );?>
Domain:out( $site['domain'] );?> + + + +
+ out( @$validation_errors['domain'] );?> +
Site Name:
Description: + +
+
+ createNonceFormField($action);?> + + + +
+ +
+ + +
+ +
+ Site Settings + +
+
P3P Compact Privacy Policy
+
This setting controls the P3P compact privacy policy that is returned to the browser when OWA sets cookies. Click here for more information on compact privacy policies and choosing the right one for your web site.
+
+
+ +
+
Domain Aliases
+
This setting allows you to specify additional domain names that you want OWA to treat as the same as the one you are using for this tracked website. For example, if the domain of your website is "www.mydomain.com" you could add an alias here for "mydomain.com". Aliases should be separated by comma.
+
+
+ + +
+
URL Parameters
+
This setting controls the URL parameters that OWA should ignore when processing requests. This is useful for avoiding duplicate URLs due to the use of tracking or others state parameters in your URLs. Parameter names should be separated by comma.
+
+
+ +
+
Default Page
+
This is the page that your web server defaults to when there is no page specified in your URL (e.g. index.html). Use this setting to combine page views for www.domain.com and www.domain.com/index.html.
+
+
+ +
+
e-commerce Reporting
+
Adds e-commerce metrics/statistics to reports.
+
+ +
+
+ +
+ + createNonceFormField('base.sitesEditSettings');?> + + + + +
+
+
+
+ Allowed Users + + +
+ createNonceFormField('base.sitesEditAllowedUsers');?> + + + + +
+ +
+
diff --git a/modules/base/templates/sites_invocation.tpl b/modules/base/templates/sites_invocation.tpl index 381f35975..dd5140761 100644 --- a/modules/base/templates/sites_invocation.tpl +++ b/modules/base/templates/sites_invocation.tpl @@ -3,6 +3,6 @@

The Domain for this web site is: out( $site->get('domain') );?>

The Site ID for this web site is: out( $site_id ); ?>

- +
diff --git a/modules/base/templates/sparklineJs.tpl b/modules/base/templates/sparklineJs.tpl index e547be3a9..40b281d59 100644 --- a/modules/base/templates/sparklineJs.tpl +++ b/modules/base/templates/sparklineJs.tpl @@ -1,4 +1,4 @@ \ No newline at end of file diff --git a/modules/base/templates/trafficSourceSum.php b/modules/base/templates/trafficSourceSum.php index 45022e069..4dbb7fe32 100644 --- a/modules/base/templates/trafficSourceSum.php +++ b/modules/base/templates/trafficSourceSum.php @@ -1,56 +1,56 @@
-
- -
Medium:
-
out( $row['medium'] );?>
- - -
Source:
-
- - out( $row['source']);?> - -
- -
-
- - -
Search Term:
-
- - out( $row['search_term'] );?> - -
- - -
- - -
- - - truncate($row['referer_page_title'], 80, '…');?>
truncate($row['referer_url'], 80, '…');?>truncate($row['referer_url'], 80, '…');?> - - - - -
- -
- +
+ +
Medium:
+
out( $row['medium'] );?>
+ + +
Source:
+
+ + out( $row['source']);?> + +
+ +
+
+ + +
Search Term:
+
+ + out( $row['search_term'] );?> + +
+ + +
+ + +
+ + + truncate($row['referer_page_title'], 80, '…');?>
truncate($row['referer_url'], 80, '…');?>truncate($row['referer_url'], 80, '…');?> + + + + +
+ +
+
\ No newline at end of file diff --git a/modules/base/templates/updates.tpl b/modules/base/templates/updates.tpl index 89307e5cb..7b8e814ce 100644 --- a/modules/base/templates/updates.tpl +++ b/modules/base/templates/updates.tpl @@ -1,33 +1,33 @@
-
-

Open Web Analytics Updater

-
-
-
- -

Some Modules need to create or update their database tables.

- -

Here is the list of modules that have updates that needs to be applied:

- -

-

    - - $module): ?> - -
  • - - - -
-

-

It is recommended that you backup your database before applying updates.

-
- -

- Apply updates -

- -
+
+

Open Web Analytics Updater

+
+
+
+ +

Some Modules need to create or update their database tables.

+ +

Here is the list of modules that have updates that needs to be applied:

+ +

+

    + + $module): ?> + +
  • + + + +
+

+

It is recommended that you backup your database before applying updates.

+
+ +

+ Apply updates +

+ +
diff --git a/modules/base/templates/users.tpl b/modules/base/templates/users.tpl index ac422923c..5f08293ae 100644 --- a/modules/base/templates/users.tpl +++ b/modules/base/templates/users.tpl @@ -1,39 +1,39 @@ -
-
-
- - - Users (Add New User) - - - - - - - - - - - - - - - $value):?> - - - - - - - - - -
User IDReal NameRoleOptions
out( $value['user_id'] );?>out( $value['real_name'] );?>out( $value['role'] );?>Edit - - | Delete
- - - There are no User Accounts. - -
+
+
+
+ + + Users (Add New User) + + + + + + + + + + + + + + + $value):?> + + + + + + + + + +
User IDReal NameRoleOptions
out( $value['user_id'] );?>out( $value['real_name'] );?>out( $value['role'] );?>Edit + + | Delete
+ + + There are no User Accounts. + +
\ No newline at end of file diff --git a/modules/base/templates/users_addoredit.tpl b/modules/base/templates/users_addoredit.tpl index 15e09bcbb..bed313221 100644 --- a/modules/base/templates/users_addoredit.tpl +++ b/modules/base/templates/users_addoredit.tpl @@ -2,73 +2,73 @@
- User Profile - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
User Name - - out( $user['user_id'] )?> - - - -
API Key
Real Name
Role - -
E-mail Address
- - createNonceFormField($action);?> - - -
+ User Profile + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
User Name + + out( $user['user_id'] )?> + + + +
API Key
Real Name
Role + +
E-mail Address
+ + createNonceFormField($action);?> + + +

- Change Password - + Change Password +
\ No newline at end of file diff --git a/modules/base/templates/users_change_password.tpl b/modules/base/templates/users_change_password.tpl index 0b308d3ef..b65a74817 100644 --- a/modules/base/templates/users_change_password.tpl +++ b/modules/base/templates/users_change_password.tpl @@ -1,35 +1,35 @@
-
Password Setup

-
Enter your new password below.

-
- - - - - - - -
- -
-
-
New Password
-

-
Re-type your Password
-

- - - -
-
-
- - - - - - - -
+
Password Setup

+
Enter your new password below.

+
+ + + + + + + +
+ +
+
+
New Password
+

+
Re-type your Password
+

+ + + +
+
+
+ + + + + + + +
diff --git a/modules/base/templates/users_password_reset_request.tpl b/modules/base/templates/users_password_reset_request.tpl index 6612ac58a..e2b30c7ac 100644 --- a/modules/base/templates/users_password_reset_request.tpl +++ b/modules/base/templates/users_password_reset_request.tpl @@ -1,50 +1,50 @@
-
Password Reset

-
Enter the e-mail address associated with your account.

-
- - - - - - - -
- -
-
-
E-mail address:
- - - - - - - -

- - - - - - -
-
- -
- - - - - - - -
- - -
- - - +
Password Reset

+
Enter the e-mail address associated with your account.

+
+ + + + + + + +
+ +
+
+
E-mail address:
+ + + + + + + +

+ + + + + + +
+
+ +
+ + + + + + + +
+ + +
+ + +
diff --git a/modules/base/templates/widget.tpl b/modules/base/templates/widget.tpl index a0f7bf6f5..d3b355598 100644 --- a/modules/base/templates/widget.tpl +++ b/modules/base/templates/widget.tpl @@ -1,41 +1,41 @@
- -
- - - - - -
- - -
- Minimize - | - Close -
-
- -
-
- " border="0" align="ABSMIDDLE"> Loading... -
- -
- -
- -
- 1): ?> - Views: - $v): ?> - / - - -
- -
- + +
+ + + + + +
+ + +
+ Minimize + | + Close +
+
+ +
+
+ " border="0" align="ABSMIDDLE"> Loading... +
+ +
+ +
+ +
+ 1): ?> + Views: + $v): ?> + / + + +
+ +
+
diff --git a/modules/base/templates/widget_inpage.tpl b/modules/base/templates/widget_inpage.tpl index beb824d42..5d2fe09e1 100644 --- a/modules/base/templates/widget_inpage.tpl +++ b/modules/base/templates/widget_inpage.tpl @@ -1,27 +1,27 @@
- - -
- 1): ?> - Views: - $v): ?> - / - - -
- - -
-
- " border="0" align="ABSMIDDLE"> Loading... -
- -
- -
- -
- + + +
+ 1): ?> + Views: + $v): ?> + / + + +
+ + +
+
+ " border="0" align="ABSMIDDLE"> Loading... +
+ +
+ +
+ +
+
diff --git a/modules/base/templates/widget_latestActions.php b/modules/base/templates/widget_latestActions.php index f630c2f74..2131175be 100644 --- a/modules/base/templates/widget_latestActions.php +++ b/modules/base/templates/widget_latestActions.php @@ -1,18 +1,18 @@
- + - - $row ):?> - - - - + + $row ):?> + + + +
- - + + out('No actions were performed during this time period.'); ?> diff --git a/modules/base/templates/wrapper_default.tpl b/modules/base/templates/wrapper_default.tpl index cabce48a5..ed0672bdd 100644 --- a/modules/base/templates/wrapper_default.tpl +++ b/modules/base/templates/wrapper_default.tpl @@ -1,27 +1,27 @@ - -getCurrentUser(); ?> - - - - Open Web Analytics - <?php echo $page_title;?> - - getTemplatePath('base','head.tpl'));?> - - - - - -
- getTemplatePath('base', 'header.tpl'));?> - - getTemplatePath('base', 'msgs.tpl'));?> - - - - getTemplatePath('base', 'footer.php'));?> -
- - + +getCurrentUser(); ?> + + + + Open Web Analytics - <?php echo $page_title;?> + + getTemplatePath('base','head.tpl'));?> + + + + + +
+ getTemplatePath('base', 'header.tpl'));?> + + getTemplatePath('base', 'msgs.tpl'));?> + + + + getTemplatePath('base', 'footer.php'));?> +
+ + \ No newline at end of file diff --git a/modules/base/templates/wrapper_email.tpl b/modules/base/templates/wrapper_email.tpl index 837fdbe66..5f2c091a3 100644 --- a/modules/base/templates/wrapper_email.tpl +++ b/modules/base/templates/wrapper_email.tpl @@ -1,3 +1,3 @@ --- Open Web Analytics ------------------------------- - - +-- Open Web Analytics ------------------------------- + + diff --git a/modules/base/templates/wrapper_gallery2.tpl b/modules/base/templates/wrapper_gallery2.tpl index d49396725..a957da07f 100644 --- a/modules/base/templates/wrapper_gallery2.tpl +++ b/modules/base/templates/wrapper_gallery2.tpl @@ -1,9 +1,9 @@ -setTemplate('css.tpl'));?> - -setTemplate('header.tpl'));?> - -setTemplate('msgs.tpl'));?> - -setTemplate('head.tpl'));?> - - +setTemplate('css.tpl'));?> + +setTemplate('header.tpl'));?> + +setTemplate('msgs.tpl'));?> + +setTemplate('head.tpl'));?> + + diff --git a/modules/base/templates/wrapper_mediawiki.tpl b/modules/base/templates/wrapper_mediawiki.tpl index 1c4cf8543..5fdc0d7f1 100644 --- a/modules/base/templates/wrapper_mediawiki.tpl +++ b/modules/base/templates/wrapper_mediawiki.tpl @@ -1,19 +1,19 @@ - - - - - - Open Web Analytics - <?php echo $page_title;?> - setTemplate('head.tpl'));?> - - - - - - setTemplate('msgs.tpl'));?> - - - - getTemplatePath('base', 'footer.php'));?> - + + + + + + Open Web Analytics - <?php echo $page_title;?> + setTemplate('head.tpl'));?> + + + + + + setTemplate('msgs.tpl'));?> + + + + getTemplatePath('base', 'footer.php'));?> + \ No newline at end of file diff --git a/modules/base/templates/wrapper_public.tpl b/modules/base/templates/wrapper_public.tpl index 880e83078..e4662363b 100644 --- a/modules/base/templates/wrapper_public.tpl +++ b/modules/base/templates/wrapper_public.tpl @@ -1,36 +1,36 @@ - - - - - - <?php echo $page_title;?> - Open Web Analytics - getTemplatePath('base','head.tpl'));?> - - - - -
- -
- setTemplate('msgs.tpl'));?> -
- - - -



-
- Web Analytics powered by Open Web Analytics - v: -
-
- - - + + + + + + <?php echo $page_title;?> - Open Web Analytics + getTemplatePath('base','head.tpl'));?> + + + + +
+ +
+ setTemplate('msgs.tpl'));?> +
+ + + +



+
+ Web Analytics powered by Open Web Analytics - v: +
+
+ + + \ No newline at end of file diff --git a/modules/base/templates/wrapper_wordpress.tpl b/modules/base/templates/wrapper_wordpress.tpl index dbe86739e..f057c3081 100644 --- a/modules/base/templates/wrapper_wordpress.tpl +++ b/modules/base/templates/wrapper_wordpress.tpl @@ -1,13 +1,13 @@ -
- -setTemplate('head.tpl'));?> - -setTemplate('header.tpl'));?> - -setTemplate('msgs.tpl'));?> - - - -getTemplatePath('base', 'footer.php'));?> - +
+ +setTemplate('head.tpl'));?> + +setTemplate('header.tpl'));?> + +setTemplate('msgs.tpl'));?> + + + +getTemplatePath('base', 'footer.php'));?> +
\ No newline at end of file diff --git a/modules/base/templates/xml_visits_geolocation.tpl b/modules/base/templates/xml_visits_geolocation.tpl index 2097f75ed..2ad659b04 100644 --- a/modules/base/templates/xml_visits_geolocation.tpl +++ b/modules/base/templates/xml_visits_geolocation.tpl @@ -1,21 +1,21 @@ - - - OWA: Visits to - Site visits for - - - - - - / at : - ]]> - - ,,5000 - - #defaultStyle - - - - - - + + + OWA: Visits to + Site visits for + + + + + - / at : + ]]> + + ,,5000 + + #defaultStyle + + + + + + \ No newline at end of file diff --git a/modules/base/updates.php b/modules/base/updates.php index a3af43607..91c5f639b 100644 --- a/modules/base/updates.php +++ b/modules/base/updates.php @@ -28,38 +28,38 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_updatesView extends owa_view { - - function render($data) { - - //switch wrapper if OWA is not embedded - // needed becasue this view might be rendered before anything else. - if (isset($this->config['is_embedded']) && $this->config['is_embedded'] != true) { - $this->t->set_template('wrapper_public.tpl'); - } - - $this->body->set_template('updates.tpl');// This is the inner template - $this->body->set('headline', 'Your database needs to be upgraded...'); - $this->body->set('modules', $data['modules']); - } + + function render($data) { + + //switch wrapper if OWA is not embedded + // needed becasue this view might be rendered before anything else. + if (isset($this->config['is_embedded']) && $this->config['is_embedded'] != true) { + $this->t->set_template('wrapper_public.tpl'); + } + + $this->body->set_template('updates.tpl');// This is the inner template + $this->body->set('headline', 'Your database needs to be upgraded...'); + $this->body->set('modules', $data['modules']); + } } class owa_updatesController extends owa_controller { - - function action() { - - $data = array(); - - $data['view_method'] = 'delegate'; - $data['view'] = 'base.updates'; - $data['modules'] = owa_coreAPI::getModulesNeedingUpdates(); - - return $data; - } + + function action() { + + $data = array(); + + $data['view_method'] = 'delegate'; + $data['view'] = 'base.updates'; + $data['modules'] = owa_coreAPI::getModulesNeedingUpdates(); + + return $data; + } } ?> diff --git a/modules/base/updates/003.php b/modules/base/updates/003.php index d20cd51ba..6983a1a2b 100644 --- a/modules/base/updates/003.php +++ b/modules/base/updates/003.php @@ -24,43 +24,43 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_base_003_update extends owa_update { - function up() { - - $db = owa_coreAPI::dbSingleton(); - $s = owa_coreAPI::serviceSingleton(); - - $entities = $s->modules[$this->module_name]->getEntities(); - - foreach ($entities as $k => $v) { - - $ret = $db->alterTableType($this->c->get('base', 'ns').$v, 'InnoDB'); - - if ($ret == true): - $this->e->notice(sprintf('Changed Table %s to InnoDB', $v)); - else: - $this->e->notice(sprintf('Change to Table %s failed', $v)); - return false; - endif; - - } - - - return true; - - - } - - function down() { - - return false; - } + function up() { + + $db = owa_coreAPI::dbSingleton(); + $s = owa_coreAPI::serviceSingleton(); + + $entities = $s->modules[$this->module_name]->getEntities(); + + foreach ($entities as $k => $v) { + + $ret = $db->alterTableType($this->c->get('base', 'ns').$v, 'InnoDB'); + + if ($ret == true): + $this->e->notice(sprintf('Changed Table %s to InnoDB', $v)); + else: + $this->e->notice(sprintf('Change to Table %s failed', $v)); + return false; + endif; + + } + + + return true; + + + } + + function down() { + + return false; + } } diff --git a/modules/base/updates/004.php b/modules/base/updates/004.php index ef8c80c88..caf0ec2b6 100644 --- a/modules/base/updates/004.php +++ b/modules/base/updates/004.php @@ -24,77 +24,77 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.2.1 + * @version $Revision$ + * @since owa 1.2.1 */ class owa_base_004_update extends owa_update { - function up() { - - // create admin user for embedded installs. - // embedded installs did not create admin users until this release (v1.2.1) - $cu = owa_coreAPI::getCurrentUser(); - $this->createAdminUser($cu->getUserData('email_address')); - - $ds = owa_coreAPI::entityFactory('base.domstream'); - $ret = $ds->createTable(); - - if ($ret == true) { - $this->e->notice('Domstream entity table created'); - return true; - } else { - $this->e->notice('Domstream entity table creation failed'); - return false; - } - } - - function down() { - - return false; - } - - function createAdminUser($email_address) { - - //create user entity - $u = owa_coreAPI::entityFactory('base.user'); - // check to see if an admin user already exists - $u->getByColumn('role', 'admin'); - $id_check = $u->get('id'); - // if not then proceed - if (empty($id_check)) { - - //Check to see if user name already exists - $u->getByColumn('user_id', 'admin'); - - $id = $u->get('id'); - - // Set user object Params - if (empty($id)) { - - $password = $u->generateRandomPassword(); - $u->set('user_id', 'admin'); - $u->set('role', 'admin'); - $u->set('real_name', ''); - $u->set('email_address', $email_address); - $u->set('password', owa_lib::encryptPassword($password)); - $u->set('creation_date', time()); - $u->set('last_update_date', time()); - $ret = $u->create(); - - owa_coreAPI::debug("Admin user created successfully."); - - return $password; - - } else { - owa_coreAPI::debug($this->getMsgAsString(3306)); - } - } else { - owa_coreAPI::debug("Admin user already exists."); - } - - } + function up() { + + // create admin user for embedded installs. + // embedded installs did not create admin users until this release (v1.2.1) + $cu = owa_coreAPI::getCurrentUser(); + $this->createAdminUser($cu->getUserData('email_address')); + + $ds = owa_coreAPI::entityFactory('base.domstream'); + $ret = $ds->createTable(); + + if ($ret == true) { + $this->e->notice('Domstream entity table created'); + return true; + } else { + $this->e->notice('Domstream entity table creation failed'); + return false; + } + } + + function down() { + + return false; + } + + function createAdminUser($email_address) { + + //create user entity + $u = owa_coreAPI::entityFactory('base.user'); + // check to see if an admin user already exists + $u->getByColumn('role', 'admin'); + $id_check = $u->get('id'); + // if not then proceed + if (empty($id_check)) { + + //Check to see if user name already exists + $u->getByColumn('user_id', 'admin'); + + $id = $u->get('id'); + + // Set user object Params + if (empty($id)) { + + $password = $u->generateRandomPassword(); + $u->set('user_id', 'admin'); + $u->set('role', 'admin'); + $u->set('real_name', ''); + $u->set('email_address', $email_address); + $u->set('password', owa_lib::encryptPassword($password)); + $u->set('creation_date', time()); + $u->set('last_update_date', time()); + $ret = $u->create(); + + owa_coreAPI::debug("Admin user created successfully."); + + return $password; + + } else { + owa_coreAPI::debug($this->getMsgAsString(3306)); + } + } else { + owa_coreAPI::debug("Admin user already exists."); + } + + } } diff --git a/modules/base/updates/005.php b/modules/base/updates/005.php index 1c9ec0b2d..086dd41ef 100644 --- a/modules/base/updates/005.php +++ b/modules/base/updates/005.php @@ -24,357 +24,357 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3 + * @version $Revision$ + * @since owa 1.3 */ class owa_base_005_update extends owa_update { - - var $schema_version = 5; - var $is_cli_mode_required = true; - - function up() { - - $tables = array('owa_session', 'owa_request', 'owa_click', 'owa_feed_request'); - - foreach ($tables as $table) { - - // add yyyymmdd column to owa_session - $db = owa_coreAPI::dbSingleton(); - $db->addColumn($table, 'yyyymmdd', 'INT'); - $db->addIndex($table, 'yyyymmdd'); - $ret = $db->query("update $table set yyyymmdd = - concat(cast(year as CHAR), lpad(CAST(month AS CHAR), 2, '0'), lpad(CAST(day AS CHAR), 2, '0')) "); - - if ($ret == true) { - $this->e->notice('Added yyyymmdd column to '.$table); - } else { - $this->e->notice('Failed to add yyyymmdd column to '.$table); - return false; - } - } - - $visitor = owa_coreAPI::entityFactory('base.visitor'); - - $ret = $visitor->addColumn('num_prior_sessions'); - - if (!$ret) { - $this->e->notice('Failed to add num_prior_sessions column to owa_visitor'); - return false; - } - - $ret = $visitor->addColumn('first_session_yyyymmdd'); - - if (!$ret) { - $this->e->notice('Failed to add first_session_yyyymmdd column to owa_visitor'); - return false; - } - - $ret = $db->query("update owa_visitor set first_session_yyyymmdd = - concat(cast(first_session_year as CHAR), lpad(CAST(first_session_month AS CHAR), 2, '0'), lpad(CAST(first_session_day AS CHAR), 2, '0')) "); - - if (!$ret) { - $this->e->notice('Failed to populate first_session_yyyymmdd column in owa_visitor'); - return false; - } - - $request = owa_coreAPI::entityFactory('base.request'); - - $ret = $request->addColumn('prior_document_id'); - - if (!$ret) { - $this->e->notice('Failed to add prior_document_id column to owa_request'); - return false; - } - - $ret = $request->addColumn('num_prior_sessions'); - - if (!$ret) { - $this->e->notice('Failed to add num_prior_sessions column to owa_request'); - return false; - } - - - $session = owa_coreAPI::entityFactory('base.session'); - - $ret = $session->addColumn('num_prior_sessions'); - - if (!$ret) { - $this->e->notice('Failed to add num_prior_sessions column to owa_session'); - return false; - } - - - $ret = $session->addColumn('is_bounce'); - - if (!$ret) { - $this->e->notice('Failed to add is_bounce column to owa_session'); - return false; - } - - $ret = $db->query("update owa_session set is_bounce = true WHERE num_pageviews = 1"); - - if (!$ret) { - $this->e->notice('Failed to populate is_bounce column in owa_session'); - return false; - } - - $ret = $session->addColumn('referring_search_term_id'); - - if (!$ret) { - $this->e->notice('Failed to add referring_search_term_id column in owa_session'); - return false; - } - - $ret = $session->addColumn('days_since_prior_session'); - - if (!$ret) { - $this->e->notice('Failed to add days_since_prior_session column in owa_session'); - return false; - } - - $ret = $db->query("update owa_session set days_since_prior_session = round(time_sinse_priorsession/(3600*24)) WHERE time_sinse_priorsession IS NOT NULL and time_sinse_priorsession > 0"); - - if (!$ret) { - $this->e->notice('Failed to populate days_since_prior_session column in owa_session'); - return false; - } - - $ret = $session->addColumn('days_since_first_session'); - - - if (!$ret) { - $this->e->notice('Failed to add days_since_first_session column in owa_session'); - return false; - } - - $ret = $db->query("update owa_session, owa_visitor set owa_session.days_since_first_session = round((owa_session.timestamp - owa_visitor.first_session_timestamp)/(3600*24)) WHERE owa_session.visitor_id = owa_visitor.id AND owa_visitor.first_session_timestamp IS NOT NULL"); - - if (!$ret) { - $this->e->notice('Failed to populate days_since_first_session column in owa_session'); - return false; - } - - // add api column - $u = owa_coreAPI::entityFactory('base.user'); - $ret = $u->addColumn('api_key'); - - if (!$ret) { - $this->e->notice('Failed to add api_key column to owa_user'); - return false; - } - - // add uri column - $d = owa_coreAPI::entityFactory('base.document'); - $d->addColumn('uri'); - $ret = $db->query("update owa_document set uri = substring_index(SUBSTR(url FROM 1+ length(substring_index(url, '/', 3))), '#', 1) "); - - if (!$ret) { - $this->e->notice('Failed to add uri column to owa_document'); - return false; - } - - $a = owa_coreAPI::entityFactory('base.action_fact'); - $ret = $a->createTable(); - - if ($ret === true) { - $this->e->notice('Action fact entity table created'); - } else { - $this->e->notice('Action fact entity table creation failed'); - return false; - } - - $st = owa_coreAPI::entityFactory('base.search_term_dim'); - $ret = $st->createTable(); - - if ($ret === true) { - $this->e->notice('Search Term Dimension entity table created'); - } else { - $this->e->notice('Search Term Dimension entity table creation failed'); - return false; - } - - // migrate search terms to new table - $ret = $db->query( - "INSERT INTO - owa_search_term_dim (id, terms, term_count) - SELECT - distinct(CRC32(LOWER(query_terms))) as id, - query_terms as terms, - length(query_terms) + 1 - length(replace(query_terms,' ','')) as term_count - FROM - owa_referer - WHERE - query_terms != ''" - ); - - if (!$ret) { - $this->e->notice('Failed to migrate search terms to new table.'); - return false; - } - - //populate search term foreign key in session table - $ret = $db->query( - "UPDATE - owa_session as session, owa_referer as referer - SET - session.referring_search_term_id = (CRC32(LOWER(referer.query_terms))) - WHERE - session.referer_id = referer.id and - session.referer_id != 0 AND - referer.query_terms != ''" - ); - - if (!$ret) { - $this->e->notice('Failed to add referring_search_term_id values to owa_session'); - return false; - } - - //populate search source in session table - $ret = $db->query( - "UPDATE - owa_session as session - SET - session.source = 'organic-search' - WHERE - session.referring_search_term_id IS NOT null" - ); - - if (!$ret) { - $this->e->notice('Failed to populate session.source values for organic-search'); - return false; - } - - //populate search source in session table - $ret = $db->query( - "UPDATE - owa_session as session - SET - session.source = 'referral' - WHERE - session.referer_id != 0 AND - session.referer_id != '' AND - session.referer_id IS NOT null AND - session.source != 'feed' AND - session.source != 'organic-search'" - ); - - if (!$ret) { - $this->e->notice('Failed to populate session.source values for referral'); - return false; - } - - - // add apiKeys to each user - $users = $db->get_results("select user_id from owa_user"); - - foreach ($users as $user) { - - $u = owa_coreAPI::entityFactory('base.user'); - $u->load($user['user_id'],'user_id'); - - if (!$u->get('api_key')) { - $u->set('api_key', $u->generateTempPasskey($u->get('user_id'))); - $u->update(); - } - } - - // change character encoding to UTF-8 - $tables = array('owa_request', 'owa_session', 'owa_feed_request', 'owa_click', 'owa_document', 'owa_ua', 'owa_site', 'owa_user', 'owa_configuration', 'owa_visitor', 'owa_os', 'owa_impression', 'owa_host', 'owa_exit','owa_domstream'); - - foreach ($tables as $table) { - - // change snippet dtd - $ret = $db->query(sprintf("ALTER TABLE %s CONVERT TO CHARACTER SET utf8", $table)); - - if (!$ret) { - $this->e->notice('Failed to change table character encoding for: ' .$table); - return false; - } - - } - - // change snippet dtd - $ret = $db->query("ALTER TABLE owa_referer MODIFY snippet MEDIUMTEXT"); - - if (!$ret) { - $this->e->notice('Failed to modify snippet column of owa_referer'); - return false; - } - - // change snippet dtd - $ret = $db->query("ALTER TABLE owa_domstream MODIFY page_url VARCHAR(255)"); - - if (!$ret) { - $this->e->notice('Failed to modify page_url column of owa_domstream'); - return false; - } - - // change snippet dtd - $ret = $db->query("ALTER TABLE owa_domstream MODIFY events MEDIUMTEXT"); - - if (!$ret) { - $this->e->notice('Failed to modify events column of owa_domstream'); - return false; - } - - // change snippet dtd - $ret = $db->query("ALTER TABLE owa_site MODIFY description MEDIUMTEXT"); - - if (!$ret) { - $this->e->notice('Failed to modify description column of owa_site'); - return false; - } - - // check for bad permissions on config file - if (file_exists(OWA_DIR . 'owa-config.php')) { - @chmod(OWA_DIR . 'owa-config.php', 0750); - } - - if (file_exists(OWA_DIR . 'conf/owa-config.php')) { - @chmod(OWA_DIR . 'conf/owa-config.php', 0750); - } - - if (file_exists(OWA_DIR . 'cli.php')) { - @chmod(OWA_DIR . 'cli.php', 0700); - } - - // must return true - return true; - } - - function down() { - - $visitor = owa_coreAPI::entityFactory('base.visitor'); - $visitor->dropColumn('num_prior_sessions'); - $visitor->dropColumn('first_session_yyyymmdd'); - $session = owa_coreAPI::entityFactory('base.session'); - $session->dropColumn('yyyymmdd'); - $session->dropColumn('is_bounce'); - $session->dropColumn('referring_search_term_id'); - $session->dropColumn('days_since_first_session'); - $session->dropColumn('days_since_prior_session'); - $session->dropColumn('num_prior_sessions'); - $request = owa_coreAPI::entityFactory('base.request'); - $request->dropColumn('yyyymmdd'); - $request->dropColumn('prior_document_id'); - $request->dropColumn('num_prior_sessions'); - $click = owa_coreAPI::entityFactory('base.click'); - $click->dropColumn('yyyymmdd'); - $feed_request = owa_coreAPI::entityFactory('base.feed_request'); - $feed_request->dropColumn('yyyymmdd'); - $u = owa_coreAPI::entityFactory('base.user'); - $u->dropColumn('api_key'); - $u = owa_coreAPI::entityFactory('base.document'); - $u->dropColumn('uri'); - $af = owa_coreAPI::entityFactory('base.action_fact'); - $af->dropTable(); - $st = owa_coreAPI::entityFactory('base.search_term_dim'); - $st->dropTable(); - - return true; - } + + var $schema_version = 5; + var $is_cli_mode_required = true; + + function up() { + + $tables = array('owa_session', 'owa_request', 'owa_click', 'owa_feed_request'); + + foreach ($tables as $table) { + + // add yyyymmdd column to owa_session + $db = owa_coreAPI::dbSingleton(); + $db->addColumn($table, 'yyyymmdd', 'INT'); + $db->addIndex($table, 'yyyymmdd'); + $ret = $db->query("update $table set yyyymmdd = + concat(cast(year as CHAR), lpad(CAST(month AS CHAR), 2, '0'), lpad(CAST(day AS CHAR), 2, '0')) "); + + if ($ret == true) { + $this->e->notice('Added yyyymmdd column to '.$table); + } else { + $this->e->notice('Failed to add yyyymmdd column to '.$table); + return false; + } + } + + $visitor = owa_coreAPI::entityFactory('base.visitor'); + + $ret = $visitor->addColumn('num_prior_sessions'); + + if (!$ret) { + $this->e->notice('Failed to add num_prior_sessions column to owa_visitor'); + return false; + } + + $ret = $visitor->addColumn('first_session_yyyymmdd'); + + if (!$ret) { + $this->e->notice('Failed to add first_session_yyyymmdd column to owa_visitor'); + return false; + } + + $ret = $db->query("update owa_visitor set first_session_yyyymmdd = + concat(cast(first_session_year as CHAR), lpad(CAST(first_session_month AS CHAR), 2, '0'), lpad(CAST(first_session_day AS CHAR), 2, '0')) "); + + if (!$ret) { + $this->e->notice('Failed to populate first_session_yyyymmdd column in owa_visitor'); + return false; + } + + $request = owa_coreAPI::entityFactory('base.request'); + + $ret = $request->addColumn('prior_document_id'); + + if (!$ret) { + $this->e->notice('Failed to add prior_document_id column to owa_request'); + return false; + } + + $ret = $request->addColumn('num_prior_sessions'); + + if (!$ret) { + $this->e->notice('Failed to add num_prior_sessions column to owa_request'); + return false; + } + + + $session = owa_coreAPI::entityFactory('base.session'); + + $ret = $session->addColumn('num_prior_sessions'); + + if (!$ret) { + $this->e->notice('Failed to add num_prior_sessions column to owa_session'); + return false; + } + + + $ret = $session->addColumn('is_bounce'); + + if (!$ret) { + $this->e->notice('Failed to add is_bounce column to owa_session'); + return false; + } + + $ret = $db->query("update owa_session set is_bounce = true WHERE num_pageviews = 1"); + + if (!$ret) { + $this->e->notice('Failed to populate is_bounce column in owa_session'); + return false; + } + + $ret = $session->addColumn('referring_search_term_id'); + + if (!$ret) { + $this->e->notice('Failed to add referring_search_term_id column in owa_session'); + return false; + } + + $ret = $session->addColumn('days_since_prior_session'); + + if (!$ret) { + $this->e->notice('Failed to add days_since_prior_session column in owa_session'); + return false; + } + + $ret = $db->query("update owa_session set days_since_prior_session = round(time_sinse_priorsession/(3600*24)) WHERE time_sinse_priorsession IS NOT NULL and time_sinse_priorsession > 0"); + + if (!$ret) { + $this->e->notice('Failed to populate days_since_prior_session column in owa_session'); + return false; + } + + $ret = $session->addColumn('days_since_first_session'); + + + if (!$ret) { + $this->e->notice('Failed to add days_since_first_session column in owa_session'); + return false; + } + + $ret = $db->query("update owa_session, owa_visitor set owa_session.days_since_first_session = round((owa_session.timestamp - owa_visitor.first_session_timestamp)/(3600*24)) WHERE owa_session.visitor_id = owa_visitor.id AND owa_visitor.first_session_timestamp IS NOT NULL"); + + if (!$ret) { + $this->e->notice('Failed to populate days_since_first_session column in owa_session'); + return false; + } + + // add api column + $u = owa_coreAPI::entityFactory('base.user'); + $ret = $u->addColumn('api_key'); + + if (!$ret) { + $this->e->notice('Failed to add api_key column to owa_user'); + return false; + } + + // add uri column + $d = owa_coreAPI::entityFactory('base.document'); + $d->addColumn('uri'); + $ret = $db->query("update owa_document set uri = substring_index(SUBSTR(url FROM 1+ length(substring_index(url, '/', 3))), '#', 1) "); + + if (!$ret) { + $this->e->notice('Failed to add uri column to owa_document'); + return false; + } + + $a = owa_coreAPI::entityFactory('base.action_fact'); + $ret = $a->createTable(); + + if ($ret === true) { + $this->e->notice('Action fact entity table created'); + } else { + $this->e->notice('Action fact entity table creation failed'); + return false; + } + + $st = owa_coreAPI::entityFactory('base.search_term_dim'); + $ret = $st->createTable(); + + if ($ret === true) { + $this->e->notice('Search Term Dimension entity table created'); + } else { + $this->e->notice('Search Term Dimension entity table creation failed'); + return false; + } + + // migrate search terms to new table + $ret = $db->query( + "INSERT INTO + owa_search_term_dim (id, terms, term_count) + SELECT + distinct(CRC32(LOWER(query_terms))) as id, + query_terms as terms, + length(query_terms) + 1 - length(replace(query_terms,' ','')) as term_count + FROM + owa_referer + WHERE + query_terms != ''" + ); + + if (!$ret) { + $this->e->notice('Failed to migrate search terms to new table.'); + return false; + } + + //populate search term foreign key in session table + $ret = $db->query( + "UPDATE + owa_session as session, owa_referer as referer + SET + session.referring_search_term_id = (CRC32(LOWER(referer.query_terms))) + WHERE + session.referer_id = referer.id and + session.referer_id != 0 AND + referer.query_terms != ''" + ); + + if (!$ret) { + $this->e->notice('Failed to add referring_search_term_id values to owa_session'); + return false; + } + + //populate search source in session table + $ret = $db->query( + "UPDATE + owa_session as session + SET + session.source = 'organic-search' + WHERE + session.referring_search_term_id IS NOT null" + ); + + if (!$ret) { + $this->e->notice('Failed to populate session.source values for organic-search'); + return false; + } + + //populate search source in session table + $ret = $db->query( + "UPDATE + owa_session as session + SET + session.source = 'referral' + WHERE + session.referer_id != 0 AND + session.referer_id != '' AND + session.referer_id IS NOT null AND + session.source != 'feed' AND + session.source != 'organic-search'" + ); + + if (!$ret) { + $this->e->notice('Failed to populate session.source values for referral'); + return false; + } + + + // add apiKeys to each user + $users = $db->get_results("select user_id from owa_user"); + + foreach ($users as $user) { + + $u = owa_coreAPI::entityFactory('base.user'); + $u->load($user['user_id'],'user_id'); + + if (!$u->get('api_key')) { + $u->set('api_key', $u->generateTempPasskey($u->get('user_id'))); + $u->update(); + } + } + + // change character encoding to UTF-8 + $tables = array('owa_request', 'owa_session', 'owa_feed_request', 'owa_click', 'owa_document', 'owa_ua', 'owa_site', 'owa_user', 'owa_configuration', 'owa_visitor', 'owa_os', 'owa_impression', 'owa_host', 'owa_exit','owa_domstream'); + + foreach ($tables as $table) { + + // change snippet dtd + $ret = $db->query(sprintf("ALTER TABLE %s CONVERT TO CHARACTER SET utf8", $table)); + + if (!$ret) { + $this->e->notice('Failed to change table character encoding for: ' .$table); + return false; + } + + } + + // change snippet dtd + $ret = $db->query("ALTER TABLE owa_referer MODIFY snippet MEDIUMTEXT"); + + if (!$ret) { + $this->e->notice('Failed to modify snippet column of owa_referer'); + return false; + } + + // change snippet dtd + $ret = $db->query("ALTER TABLE owa_domstream MODIFY page_url VARCHAR(255)"); + + if (!$ret) { + $this->e->notice('Failed to modify page_url column of owa_domstream'); + return false; + } + + // change snippet dtd + $ret = $db->query("ALTER TABLE owa_domstream MODIFY events MEDIUMTEXT"); + + if (!$ret) { + $this->e->notice('Failed to modify events column of owa_domstream'); + return false; + } + + // change snippet dtd + $ret = $db->query("ALTER TABLE owa_site MODIFY description MEDIUMTEXT"); + + if (!$ret) { + $this->e->notice('Failed to modify description column of owa_site'); + return false; + } + + // check for bad permissions on config file + if (file_exists(OWA_DIR . 'owa-config.php')) { + @chmod(OWA_DIR . 'owa-config.php', 0750); + } + + if (file_exists(OWA_DIR . 'conf/owa-config.php')) { + @chmod(OWA_DIR . 'conf/owa-config.php', 0750); + } + + if (file_exists(OWA_DIR . 'cli.php')) { + @chmod(OWA_DIR . 'cli.php', 0700); + } + + // must return true + return true; + } + + function down() { + + $visitor = owa_coreAPI::entityFactory('base.visitor'); + $visitor->dropColumn('num_prior_sessions'); + $visitor->dropColumn('first_session_yyyymmdd'); + $session = owa_coreAPI::entityFactory('base.session'); + $session->dropColumn('yyyymmdd'); + $session->dropColumn('is_bounce'); + $session->dropColumn('referring_search_term_id'); + $session->dropColumn('days_since_first_session'); + $session->dropColumn('days_since_prior_session'); + $session->dropColumn('num_prior_sessions'); + $request = owa_coreAPI::entityFactory('base.request'); + $request->dropColumn('yyyymmdd'); + $request->dropColumn('prior_document_id'); + $request->dropColumn('num_prior_sessions'); + $click = owa_coreAPI::entityFactory('base.click'); + $click->dropColumn('yyyymmdd'); + $feed_request = owa_coreAPI::entityFactory('base.feed_request'); + $feed_request->dropColumn('yyyymmdd'); + $u = owa_coreAPI::entityFactory('base.user'); + $u->dropColumn('api_key'); + $u = owa_coreAPI::entityFactory('base.document'); + $u->dropColumn('uri'); + $af = owa_coreAPI::entityFactory('base.action_fact'); + $af->dropTable(); + $st = owa_coreAPI::entityFactory('base.search_term_dim'); + $st->dropTable(); + + return true; + } } ?> \ No newline at end of file diff --git a/modules/base/updates/006.php b/modules/base/updates/006.php index 977b39300..f60fb67dc 100644 --- a/modules/base/updates/006.php +++ b/modules/base/updates/006.php @@ -24,259 +24,259 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_base_006_update extends owa_update { - - var $schema_version = 6; - var $is_cli_mode_required = true; - - function up() { - - $session = owa_coreAPI::entityFactory('base.session'); - $session_columns = array( - 'num_goals', - 'num_goal_starts', - 'goals_value', - 'location_id', - 'language', - 'source_id', - 'ad_id', - 'campaign_id', - 'latest_attributions', - 'commerce_trans_count', - 'commerce_trans_revenue', - 'commerce_items_revenue', - 'commerce_items_count', - 'commerce_items_quantity', - 'commerce_shipping_revenue', - 'commerce_tax_revenue'); - - // create goal related columns - $goals = owa_coreAPI::getSetting('base', 'numGoals'); - - for ($i=1; $i <= $goals; $i++ ) { - $session_columns[] = 'goal_'.$i; - $session_columns[] = 'goal_'.$i.'_start'; - $session_columns[] = 'goal_'.$i.'_value'; - } - // add columns to owa_session - foreach ( $session_columns as $session_col_name ) { - $ret = $session->addColumn( $session_col_name ); - if ( $ret === true ) { - $this->e->notice( "$session_col_name added to owa_session" ); - } else { - $this->e->notice( "Adding $session_col_name to owa_session failed." ); - return false; - } - } - //rename col - $ret = $session->renameColumn('source', 'medium'); - if (!$ret) { - $this->e->notice('Failed to rename source column to medium in owa_session'); - return false; - } - - $request = owa_coreAPI::entityFactory('base.request'); - $request_columns = array( - 'location_id', - 'language'); - - // add columns to owa_session - foreach ( $request_columns as $request_col_name ) { - $ret = $request->addColumn( $request_col_name ); - if ( $ret === true ) { - $this->e->notice( "$request_col_name added to owa_request" ); - } else { - $this->e->notice( "Adding $request_col_name to owa_request failed." ); - return false; - } - } - - $domstream = owa_coreAPI::entityFactory('base.domstream'); - $ret = $domstream->addColumn('domstream_guid'); - - if ( $ret === true ) { - $this->e->notice( "domstream_guid added to owa_domstream" ); - } else { - $this->e->notice( "Adding domstream_guid to owa_domstream failed." ); - return false; - } - - $db = owa_coreAPI::dbSingleton(); - $ret = $db->query("update owa_domstream set domstream_guid = id"); - - $site = owa_coreAPI::entityFactory('base.site'); - $ret = $site->addColumn('settings'); - - if ( $ret === true ) { - $this->e->notice( "settings added to owa_site" ); - } else { - $this->e->notice( "Adding settings to owa_site failed." ); - return false; - } - //$db->query("alter table owa_site DROP PRIMARY KEY"); - $db->query("ALTER TABLE owa_site ADD id_1_3 INT"); - if ( $ret === true ) { - $this->e->notice( "id_1_3 column added to owa_site" ); - } else { - $this->e->notice( "adding id_1_3 column to owa_site failed." ); - return false; - } - - $ret = $db->query("update owa_site set id_1_3 = id"); - if ( $ret === true ) { - $this->e->notice( "populating id_1_3 in owa_site." ); - } else { - $this->e->notice( "population of id_1_3 column in owa_site failed." ); - return false; - } - - $ret = $db->query('ALTER TABLE owa_site MODIFY id BIGINT'); - if ( $ret === true ) { - $this->e->notice( "id column modified in owa_site" ); - } else { - $this->e->notice( "modify of id column in owa_site failed." ); - return false; - } - - $ret = $db->query("update owa_site set id = CRC32(site_id)"); - if ( $ret === true ) { - $this->e->notice( "populating id column in owa_site was successful." ); - } else { - $this->e->notice( "populating id column in owa_site failed." ); - return false; - } - - $click = owa_coreAPI::entityFactory('base.click'); - $ret = $click->addColumn('dom_element_class'); - - if ( $ret === true ) { - $this->e->notice( "dom_element_class added to owa_click" ); - } else { - $this->e->notice( "Adding dom_element_class to owa_click failed." ); - return false; - } - - $ret = $click->addColumn('dom_element_parent_id'); - - if ( $ret === true ) { - $this->e->notice( "dom_element_parent_id added to owa_click" ); - } else { - $this->e->notice( "Adding dom_element_parent_id to owa_click failed." ); - return false; - } - - - //create new entitiy tables - $new_entities = array( - 'base.ad_dim', - 'base.source_dim', - 'base.campaign_dim', - 'base.location_dim', - 'base.commerce_transaction_fact', - 'base.commerce_line_item_fact', - 'base.queue_item'); - - foreach ($new_entities as $entity_name) { - $entity = owa_coreAPI::entityFactory($entity_name); - $ret = $entity->createTable(); - - if ($ret === true) { - $this->e->notice("$entity_name table created."); - } else { - $this->e->notice("$entity_name table failed."); - return false; - } - } - - // must return true - return true; - } - - function down() { - - $session = owa_coreAPI::entityFactory('base.session'); - // owa_session columns to drop - $session_columns = array( - 'num_goals', - 'num_goal_starts', - 'goals_value', - 'location_id', - 'language', - 'source_id', - 'ad_id', - 'campaign_id', - 'latest_attributions', - 'commerce_trans_count', - 'commerce_trans_revenue', - 'commerce_items_revenue', - 'commerce_items_count', - 'commerce_items_quantity', - 'commerce_shipping_revenue', - 'commerce_tax_revenue'); - - // add in goal related columns - $goals = owa_coreAPI::getSetting('base', 'numGoals'); - for ($i=1; $i <= $goals; $i++ ) { - $session_columns[] = 'goal_'.$i; - $session_columns[] = 'goal_'.$i.'_start'; - $session_columns[] = 'goal_'.$i.'_value'; - } - //drop columns from owa_session - foreach ($session_columns as $session_col_name) { - $session->dropColumn($session_col_name); - } - //rename col back to original - $session->renameColumn('medium', 'source', true); - - //drop request columns - $request = owa_coreAPI::entityFactory('base.request'); - $request_columns = array( - 'location_id', - 'language'); - - // add columns to owa_session - foreach ( $request_columns as $request_col_name ) { - $ret = $request->dropColumn( $request_col_name ); - } - - $domstream = owa_coreAPI::entityFactory('base.domstream'); - $domstream->dropColumn('domstream_guid'); - - $site = owa_coreAPI::entityFactory('base.site'); - $site->dropColumn('settings'); - //$site->modifyColumn('id'); - $db = owa_coreAPI::dbSingleton(); - $db->query('ALTER TABLE owa_site MODIFY id SERIAL'); - $db->query('UPDATE owa_site SET id = id_1_3'); - $ret = $db->query('ALTER TABLE owa_site MODIFY id INT'); - $db->query('ALTER TABLE owa_site DROP id_1_3'); - - $click = owa_coreAPI::entityFactory('base.click'); - $click->dropColumn('dom_element_class'); - $click->dropColumn('dom_element_parent_id'); - - //drop tables - $new_entities = array( - 'base.ad_dim', - 'base.source_dim', - 'base.campaign_dim', - 'base.location_dim', - 'base.commerce_transaction_fact', - 'base.commerce_line_item_fact', - 'base.queue_item'); - - foreach ($new_entities as $entity_name) { - $entity = owa_coreAPI::entityFactory($entity_name); - $ret = $entity->dropTable(); - } - - return true; - } + + var $schema_version = 6; + var $is_cli_mode_required = true; + + function up() { + + $session = owa_coreAPI::entityFactory('base.session'); + $session_columns = array( + 'num_goals', + 'num_goal_starts', + 'goals_value', + 'location_id', + 'language', + 'source_id', + 'ad_id', + 'campaign_id', + 'latest_attributions', + 'commerce_trans_count', + 'commerce_trans_revenue', + 'commerce_items_revenue', + 'commerce_items_count', + 'commerce_items_quantity', + 'commerce_shipping_revenue', + 'commerce_tax_revenue'); + + // create goal related columns + $goals = owa_coreAPI::getSetting('base', 'numGoals'); + + for ($i=1; $i <= $goals; $i++ ) { + $session_columns[] = 'goal_'.$i; + $session_columns[] = 'goal_'.$i.'_start'; + $session_columns[] = 'goal_'.$i.'_value'; + } + // add columns to owa_session + foreach ( $session_columns as $session_col_name ) { + $ret = $session->addColumn( $session_col_name ); + if ( $ret === true ) { + $this->e->notice( "$session_col_name added to owa_session" ); + } else { + $this->e->notice( "Adding $session_col_name to owa_session failed." ); + return false; + } + } + //rename col + $ret = $session->renameColumn('source', 'medium'); + if (!$ret) { + $this->e->notice('Failed to rename source column to medium in owa_session'); + return false; + } + + $request = owa_coreAPI::entityFactory('base.request'); + $request_columns = array( + 'location_id', + 'language'); + + // add columns to owa_session + foreach ( $request_columns as $request_col_name ) { + $ret = $request->addColumn( $request_col_name ); + if ( $ret === true ) { + $this->e->notice( "$request_col_name added to owa_request" ); + } else { + $this->e->notice( "Adding $request_col_name to owa_request failed." ); + return false; + } + } + + $domstream = owa_coreAPI::entityFactory('base.domstream'); + $ret = $domstream->addColumn('domstream_guid'); + + if ( $ret === true ) { + $this->e->notice( "domstream_guid added to owa_domstream" ); + } else { + $this->e->notice( "Adding domstream_guid to owa_domstream failed." ); + return false; + } + + $db = owa_coreAPI::dbSingleton(); + $ret = $db->query("update owa_domstream set domstream_guid = id"); + + $site = owa_coreAPI::entityFactory('base.site'); + $ret = $site->addColumn('settings'); + + if ( $ret === true ) { + $this->e->notice( "settings added to owa_site" ); + } else { + $this->e->notice( "Adding settings to owa_site failed." ); + return false; + } + //$db->query("alter table owa_site DROP PRIMARY KEY"); + $db->query("ALTER TABLE owa_site ADD id_1_3 INT"); + if ( $ret === true ) { + $this->e->notice( "id_1_3 column added to owa_site" ); + } else { + $this->e->notice( "adding id_1_3 column to owa_site failed." ); + return false; + } + + $ret = $db->query("update owa_site set id_1_3 = id"); + if ( $ret === true ) { + $this->e->notice( "populating id_1_3 in owa_site." ); + } else { + $this->e->notice( "population of id_1_3 column in owa_site failed." ); + return false; + } + + $ret = $db->query('ALTER TABLE owa_site MODIFY id BIGINT'); + if ( $ret === true ) { + $this->e->notice( "id column modified in owa_site" ); + } else { + $this->e->notice( "modify of id column in owa_site failed." ); + return false; + } + + $ret = $db->query("update owa_site set id = CRC32(site_id)"); + if ( $ret === true ) { + $this->e->notice( "populating id column in owa_site was successful." ); + } else { + $this->e->notice( "populating id column in owa_site failed." ); + return false; + } + + $click = owa_coreAPI::entityFactory('base.click'); + $ret = $click->addColumn('dom_element_class'); + + if ( $ret === true ) { + $this->e->notice( "dom_element_class added to owa_click" ); + } else { + $this->e->notice( "Adding dom_element_class to owa_click failed." ); + return false; + } + + $ret = $click->addColumn('dom_element_parent_id'); + + if ( $ret === true ) { + $this->e->notice( "dom_element_parent_id added to owa_click" ); + } else { + $this->e->notice( "Adding dom_element_parent_id to owa_click failed." ); + return false; + } + + + //create new entitiy tables + $new_entities = array( + 'base.ad_dim', + 'base.source_dim', + 'base.campaign_dim', + 'base.location_dim', + 'base.commerce_transaction_fact', + 'base.commerce_line_item_fact', + 'base.queue_item'); + + foreach ($new_entities as $entity_name) { + $entity = owa_coreAPI::entityFactory($entity_name); + $ret = $entity->createTable(); + + if ($ret === true) { + $this->e->notice("$entity_name table created."); + } else { + $this->e->notice("$entity_name table failed."); + return false; + } + } + + // must return true + return true; + } + + function down() { + + $session = owa_coreAPI::entityFactory('base.session'); + // owa_session columns to drop + $session_columns = array( + 'num_goals', + 'num_goal_starts', + 'goals_value', + 'location_id', + 'language', + 'source_id', + 'ad_id', + 'campaign_id', + 'latest_attributions', + 'commerce_trans_count', + 'commerce_trans_revenue', + 'commerce_items_revenue', + 'commerce_items_count', + 'commerce_items_quantity', + 'commerce_shipping_revenue', + 'commerce_tax_revenue'); + + // add in goal related columns + $goals = owa_coreAPI::getSetting('base', 'numGoals'); + for ($i=1; $i <= $goals; $i++ ) { + $session_columns[] = 'goal_'.$i; + $session_columns[] = 'goal_'.$i.'_start'; + $session_columns[] = 'goal_'.$i.'_value'; + } + //drop columns from owa_session + foreach ($session_columns as $session_col_name) { + $session->dropColumn($session_col_name); + } + //rename col back to original + $session->renameColumn('medium', 'source', true); + + //drop request columns + $request = owa_coreAPI::entityFactory('base.request'); + $request_columns = array( + 'location_id', + 'language'); + + // add columns to owa_session + foreach ( $request_columns as $request_col_name ) { + $ret = $request->dropColumn( $request_col_name ); + } + + $domstream = owa_coreAPI::entityFactory('base.domstream'); + $domstream->dropColumn('domstream_guid'); + + $site = owa_coreAPI::entityFactory('base.site'); + $site->dropColumn('settings'); + //$site->modifyColumn('id'); + $db = owa_coreAPI::dbSingleton(); + $db->query('ALTER TABLE owa_site MODIFY id SERIAL'); + $db->query('UPDATE owa_site SET id = id_1_3'); + $ret = $db->query('ALTER TABLE owa_site MODIFY id INT'); + $db->query('ALTER TABLE owa_site DROP id_1_3'); + + $click = owa_coreAPI::entityFactory('base.click'); + $click->dropColumn('dom_element_class'); + $click->dropColumn('dom_element_parent_id'); + + //drop tables + $new_entities = array( + 'base.ad_dim', + 'base.source_dim', + 'base.campaign_dim', + 'base.location_dim', + 'base.commerce_transaction_fact', + 'base.commerce_line_item_fact', + 'base.queue_item'); + + foreach ($new_entities as $entity_name) { + $entity = owa_coreAPI::entityFactory($entity_name); + $ret = $entity->dropTable(); + } + + return true; + } } ?> \ No newline at end of file diff --git a/modules/base/updates/007.php b/modules/base/updates/007.php index f90954131..be640695d 100644 --- a/modules/base/updates/007.php +++ b/modules/base/updates/007.php @@ -24,333 +24,333 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.5.0 + * @version $Revision$ + * @since owa 1.5.0 */ class owa_base_007_update extends owa_update { - - var $schema_version = 7; - var $is_cli_mode_required = true; - var $entities = array(); - - function __construct() { - - $this->entities['base.action_fact']['addColumn'] = array( - 'last_req', - 'ip_address', - 'num_prior_sessions', - 'is_new_visitor', - 'is_repeat_visitor', - 'location_id', - 'language', - 'referer_id', - 'referring_search_term_id', - 'days_since_prior_session', - 'days_since_first_session', - 'medium', - 'source_id', - 'ad_id', - 'campaign_id', - 'day', - 'month', - 'year', - 'dayofweek', - 'dayofyear', - 'weekofyear', - 'user_name' - ); - - $this->entities['base.domstream']['addColumn'] = array( - 'last_req', - 'ip_address', - 'num_prior_sessions', - 'is_new_visitor', - 'is_repeat_visitor', - 'location_id', - 'language', - 'referer_id', - 'referring_search_term_id', - 'days_since_prior_session', - 'days_since_first_session', - 'medium', - 'source_id', - 'ad_id', - 'campaign_id', - 'ua_id', - 'host_id', - 'os_id', - 'day', - 'month', - 'year', - 'dayofweek', - 'dayofyear', - 'weekofyear', - 'user_name' - ); - - $this->entities['base.click']['addColumn'] = array( - - 'referring_search_term_id', - 'days_since_prior_session', - 'days_since_first_session', - 'medium', - 'source_id', - 'os_id', - 'last_req', - 'num_prior_sessions', - 'is_new_visitor', - 'is_repeat_visitor', - 'location_id', - 'language', - 'referer_id', - 'user_name', - 'dayofweek' - - ); - - - $this->entities['base.request']['addColumn'] = array( - - 'referring_search_term_id', - 'days_since_prior_session', - 'days_since_first_session', - 'medium', - 'source_id', - 'ad_id', - 'campaign_id' - ); - - $this->entities['base.commerce_transaction_fact']['addColumn'] = array( - - 'days_since_prior_session', - 'last_req', - 'language', - 'ip_address', - 'is_new_visitor', - 'is_repeat_visitor', - 'day', - 'month', - 'year', - 'dayofweek', - 'dayofyear', - 'weekofyear', - 'user_name' - - ); - - $this->entities['base.commerce_line_item_fact']['addColumn'] = array( - - 'days_since_prior_session', - 'days_since_first_session', - 'num_prior_sessions', - 'last_req', - 'language', - 'ip_address', - 'is_new_visitor', - 'is_repeat_visitor', - 'referer_id', - 'day', - 'month', - 'year', - 'dayofweek', - 'dayofyear', - 'weekofyear', - 'user_name' - - ); - - // custom variable columns - $cv_max = owa_coreAPI::getSetting( 'base', 'maxCustomVars' ); - $fact_table_entities = array( - 'base.action_fact', - 'base.request', - 'base.session', - 'base.domstream', - 'base.click', - 'base.commerce_transaction_fact', - 'base.commerce_line_item_fact', - - ); - - for ($i = 1; $i <= $cv_max;$i++) { - - foreach( $fact_table_entities as $fact_table_entity ) { - - $this->entities[$fact_table_entity]['addColumn'][] = 'cv'.$i.'_name'; - $this->entities[$fact_table_entity]['addColumn'][] = 'cv'.$i.'_value'; - } - - } - - return parent::__construct(); - } - - function up($force = false) { - - foreach ( $this->entities as $entity => $operations) { - $e = owa_coreAPI::entityFactory($entity); - foreach ( $operations as $operation => $items ) { - foreach ($items as $item) { - $ret = $e->$operation( $item ); - if ( $ret === true ) { - $this->e->notice( "Applied $operation on $entity for $item" ); - } else { - - if ( ! $force ) { - $this->e->notice( "Applying $operation on $entity for $item failed." ); - return false; - } else { - $this->e->notice( "Forced $operation on $entity for $item failed." ); - } - } - } - } - } - - // convert text cols to blobs for storing serialized data - - $db = owa_coreAPI::dbSingleton(); - - $ret = $db->query('ALTER TABLE owa_queue_item MODIFY event BLOB'); - if ( $ret === true ) { - $this->e->notice( "event column modified in owa_queue_item" ); - } else { - $this->e->notice( "modify of event column in owa_queue_item failed." ); - return false; - } - - $ret = $db->query('ALTER TABLE owa_click MODIFY target_url VARCHAR(255)'); - if ( $ret === true ) { - $this->e->notice( "target_url column modified in owa_click" ); - } else { - $this->e->notice( "modify of target_url column in owa_click failed." ); - return false; - } - - - $ret = $db->query('ALTER TABLE owa_session MODIFY latest_attributions BLOB'); - if ( $ret === true ) { - $this->e->notice( "latest_attributions column modified in owa_session" ); - } else { - $this->e->notice( "modify of latest_attributions column in owa_session failed." ); - return false; - } - - $ret = $db->query('ALTER TABLE owa_site MODIFY settings BLOB'); - if ( $ret === true ) { - $this->e->notice( "settings column modified in owa_site" ); - } else { - $this->e->notice( "modify of settings column in owa_site failed." ); - return false; - } - - $ret = $db->query('ALTER TABLE owa_configuration MODIFY settings BLOB'); - if ( $ret === true ) { - $this->e->notice( "settings column modified in owa_configuration" ); - } else { - $this->e->notice( "modify of settings column in owa_configuration failed." ); - return false; - } - - $ret = $db->query('ALTER TABLE owa_domstream MODIFY events BLOB'); - if ( $ret === true ) { - $this->e->notice( "events column modified in owa_domstream" ); - } else { - $this->e->notice( "modify of events column in owa_domstream failed." ); - return false; - } - - // migrate month column - $fact_table = array( - 'owa_request', - 'owa_session', - 'owa_action_fact', - 'owa_domstream', - 'owa_commerce_line_item_fact', - 'owa_commerce_transaction_fact', - 'owa_click' - ); - - foreach ($fact_table as $table) { - - $ret = $db->query( - "update $table set month = concat(cast(year as CHAR), lpad(CAST(month AS CHAR), 2, '0'))" - ); - - if ($ret == true) { - $this->e->notice('Updated month column in '.$table); - } else { - $this->e->notice('Failed to update month column in '.$table); - return false; - } - - // add site_id index - $db->addIndex( $table, 'site_id' ); - - if ( $table != 'owa_session' ) { - $db->addIndex( $table, 'session_id' ); - } - } - - // add indexes - $db->addIndex( 'owa_action_fact', 'yyyymmdd' ); - - $db->addIndex( 'owa_action_fact', 'action_group, action_name' ); - $db->addIndex( 'owa_commerce_transaction_fact', 'yyyymmdd' ); - $db->addIndex( 'owa_commerce_line_item_fact', 'yyyymmdd' ); - $db->addIndex( 'owa_queue_item', 'status' ); - $db->addIndex( 'owa_queue_item', 'event_type' ); - $db->addIndex( 'owa_queue_item', 'not_before_timestamp' ); - $db->addIndex( 'owa_domstream', 'yyyymmdd' ); - $db->addIndex( 'owa_domstream', 'domstream_guid' ); - $db->addIndex( 'owa_domstream', 'document_id' ); - - - // must return true - return true; - } - - function down() { - - foreach ( $this->entities as $entity => $operations) { - - $e = owa_coreAPI::entityFactory($entity); - - foreach ( $operations as $operation => $items ) { - - foreach ($items as $item) { - - if ($operation === 'addColumn') { - $operation = 'dropColumn'; - } - $ret = $e->$operation( $item ); - if ( $ret === true ) { - $this->e->notice( "Applied $operation on $entity for $item" ); - } else { - $this->e->notice( "Applying $operation on $entity for $item failed." ); - - } - } - } - } - - // drop indexes - $db = owa_coreAPI::dbSingleton(); - $db->dropIndex( 'owa_action_fact', 'yyyymmdd' ); - $db->dropIndex( 'owa_action_fact', 'action_group' ); - $db->dropIndex( 'owa_commerce_transaction_fact', 'yyyymmdd' ); - $db->dropIndex( 'owa_commerce_line_item_fact', 'yyyymmdd' ); - $db->dropIndex( 'owa_queue_item', 'status' ); - $db->dropIndex( 'owa_queue_item', 'event_type' ); - $db->dropIndex( 'owa_queue_item', 'not_before_timestamp' ); - $db->dropIndex( 'owa_domstream', 'yyyymmdd' ); - $db->dropIndex( 'owa_domstream', 'domstream_guid' ); - $db->dropIndex( 'owa_domstream', 'document_id' ); - - return true; - } + + var $schema_version = 7; + var $is_cli_mode_required = true; + var $entities = array(); + + function __construct() { + + $this->entities['base.action_fact']['addColumn'] = array( + 'last_req', + 'ip_address', + 'num_prior_sessions', + 'is_new_visitor', + 'is_repeat_visitor', + 'location_id', + 'language', + 'referer_id', + 'referring_search_term_id', + 'days_since_prior_session', + 'days_since_first_session', + 'medium', + 'source_id', + 'ad_id', + 'campaign_id', + 'day', + 'month', + 'year', + 'dayofweek', + 'dayofyear', + 'weekofyear', + 'user_name' + ); + + $this->entities['base.domstream']['addColumn'] = array( + 'last_req', + 'ip_address', + 'num_prior_sessions', + 'is_new_visitor', + 'is_repeat_visitor', + 'location_id', + 'language', + 'referer_id', + 'referring_search_term_id', + 'days_since_prior_session', + 'days_since_first_session', + 'medium', + 'source_id', + 'ad_id', + 'campaign_id', + 'ua_id', + 'host_id', + 'os_id', + 'day', + 'month', + 'year', + 'dayofweek', + 'dayofyear', + 'weekofyear', + 'user_name' + ); + + $this->entities['base.click']['addColumn'] = array( + + 'referring_search_term_id', + 'days_since_prior_session', + 'days_since_first_session', + 'medium', + 'source_id', + 'os_id', + 'last_req', + 'num_prior_sessions', + 'is_new_visitor', + 'is_repeat_visitor', + 'location_id', + 'language', + 'referer_id', + 'user_name', + 'dayofweek' + + ); + + + $this->entities['base.request']['addColumn'] = array( + + 'referring_search_term_id', + 'days_since_prior_session', + 'days_since_first_session', + 'medium', + 'source_id', + 'ad_id', + 'campaign_id' + ); + + $this->entities['base.commerce_transaction_fact']['addColumn'] = array( + + 'days_since_prior_session', + 'last_req', + 'language', + 'ip_address', + 'is_new_visitor', + 'is_repeat_visitor', + 'day', + 'month', + 'year', + 'dayofweek', + 'dayofyear', + 'weekofyear', + 'user_name' + + ); + + $this->entities['base.commerce_line_item_fact']['addColumn'] = array( + + 'days_since_prior_session', + 'days_since_first_session', + 'num_prior_sessions', + 'last_req', + 'language', + 'ip_address', + 'is_new_visitor', + 'is_repeat_visitor', + 'referer_id', + 'day', + 'month', + 'year', + 'dayofweek', + 'dayofyear', + 'weekofyear', + 'user_name' + + ); + + // custom variable columns + $cv_max = owa_coreAPI::getSetting( 'base', 'maxCustomVars' ); + $fact_table_entities = array( + 'base.action_fact', + 'base.request', + 'base.session', + 'base.domstream', + 'base.click', + 'base.commerce_transaction_fact', + 'base.commerce_line_item_fact', + + ); + + for ($i = 1; $i <= $cv_max;$i++) { + + foreach( $fact_table_entities as $fact_table_entity ) { + + $this->entities[$fact_table_entity]['addColumn'][] = 'cv'.$i.'_name'; + $this->entities[$fact_table_entity]['addColumn'][] = 'cv'.$i.'_value'; + } + + } + + return parent::__construct(); + } + + function up($force = false) { + + foreach ( $this->entities as $entity => $operations) { + $e = owa_coreAPI::entityFactory($entity); + foreach ( $operations as $operation => $items ) { + foreach ($items as $item) { + $ret = $e->$operation( $item ); + if ( $ret === true ) { + $this->e->notice( "Applied $operation on $entity for $item" ); + } else { + + if ( ! $force ) { + $this->e->notice( "Applying $operation on $entity for $item failed." ); + return false; + } else { + $this->e->notice( "Forced $operation on $entity for $item failed." ); + } + } + } + } + } + + // convert text cols to blobs for storing serialized data + + $db = owa_coreAPI::dbSingleton(); + + $ret = $db->query('ALTER TABLE owa_queue_item MODIFY event BLOB'); + if ( $ret === true ) { + $this->e->notice( "event column modified in owa_queue_item" ); + } else { + $this->e->notice( "modify of event column in owa_queue_item failed." ); + return false; + } + + $ret = $db->query('ALTER TABLE owa_click MODIFY target_url VARCHAR(255)'); + if ( $ret === true ) { + $this->e->notice( "target_url column modified in owa_click" ); + } else { + $this->e->notice( "modify of target_url column in owa_click failed." ); + return false; + } + + + $ret = $db->query('ALTER TABLE owa_session MODIFY latest_attributions BLOB'); + if ( $ret === true ) { + $this->e->notice( "latest_attributions column modified in owa_session" ); + } else { + $this->e->notice( "modify of latest_attributions column in owa_session failed." ); + return false; + } + + $ret = $db->query('ALTER TABLE owa_site MODIFY settings BLOB'); + if ( $ret === true ) { + $this->e->notice( "settings column modified in owa_site" ); + } else { + $this->e->notice( "modify of settings column in owa_site failed." ); + return false; + } + + $ret = $db->query('ALTER TABLE owa_configuration MODIFY settings BLOB'); + if ( $ret === true ) { + $this->e->notice( "settings column modified in owa_configuration" ); + } else { + $this->e->notice( "modify of settings column in owa_configuration failed." ); + return false; + } + + $ret = $db->query('ALTER TABLE owa_domstream MODIFY events BLOB'); + if ( $ret === true ) { + $this->e->notice( "events column modified in owa_domstream" ); + } else { + $this->e->notice( "modify of events column in owa_domstream failed." ); + return false; + } + + // migrate month column + $fact_table = array( + 'owa_request', + 'owa_session', + 'owa_action_fact', + 'owa_domstream', + 'owa_commerce_line_item_fact', + 'owa_commerce_transaction_fact', + 'owa_click' + ); + + foreach ($fact_table as $table) { + + $ret = $db->query( + "update $table set month = concat(cast(year as CHAR), lpad(CAST(month AS CHAR), 2, '0'))" + ); + + if ($ret == true) { + $this->e->notice('Updated month column in '.$table); + } else { + $this->e->notice('Failed to update month column in '.$table); + return false; + } + + // add site_id index + $db->addIndex( $table, 'site_id' ); + + if ( $table != 'owa_session' ) { + $db->addIndex( $table, 'session_id' ); + } + } + + // add indexes + $db->addIndex( 'owa_action_fact', 'yyyymmdd' ); + + $db->addIndex( 'owa_action_fact', 'action_group, action_name' ); + $db->addIndex( 'owa_commerce_transaction_fact', 'yyyymmdd' ); + $db->addIndex( 'owa_commerce_line_item_fact', 'yyyymmdd' ); + $db->addIndex( 'owa_queue_item', 'status' ); + $db->addIndex( 'owa_queue_item', 'event_type' ); + $db->addIndex( 'owa_queue_item', 'not_before_timestamp' ); + $db->addIndex( 'owa_domstream', 'yyyymmdd' ); + $db->addIndex( 'owa_domstream', 'domstream_guid' ); + $db->addIndex( 'owa_domstream', 'document_id' ); + + + // must return true + return true; + } + + function down() { + + foreach ( $this->entities as $entity => $operations) { + + $e = owa_coreAPI::entityFactory($entity); + + foreach ( $operations as $operation => $items ) { + + foreach ($items as $item) { + + if ($operation === 'addColumn') { + $operation = 'dropColumn'; + } + $ret = $e->$operation( $item ); + if ( $ret === true ) { + $this->e->notice( "Applied $operation on $entity for $item" ); + } else { + $this->e->notice( "Applying $operation on $entity for $item failed." ); + + } + } + } + } + + // drop indexes + $db = owa_coreAPI::dbSingleton(); + $db->dropIndex( 'owa_action_fact', 'yyyymmdd' ); + $db->dropIndex( 'owa_action_fact', 'action_group' ); + $db->dropIndex( 'owa_commerce_transaction_fact', 'yyyymmdd' ); + $db->dropIndex( 'owa_commerce_line_item_fact', 'yyyymmdd' ); + $db->dropIndex( 'owa_queue_item', 'status' ); + $db->dropIndex( 'owa_queue_item', 'event_type' ); + $db->dropIndex( 'owa_queue_item', 'not_before_timestamp' ); + $db->dropIndex( 'owa_domstream', 'yyyymmdd' ); + $db->dropIndex( 'owa_domstream', 'domstream_guid' ); + $db->dropIndex( 'owa_domstream', 'document_id' ); + + return true; + } } ?> \ No newline at end of file diff --git a/modules/base/updates/008.php b/modules/base/updates/008.php index 5ab464a88..eeeceb4b3 100644 --- a/modules/base/updates/008.php +++ b/modules/base/updates/008.php @@ -23,32 +23,32 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.5.0 + * @version $Revision$ + * @since owa 1.5.0 */ class owa_base_008_update extends owa_update { - - var $schema_version = 8; - - - function up($force = false) { - $site = owa_coreAPI::entityFactory('base.site_user'); - $ret = $site->createTable('site_user'); - if ($ret === false ) { - $this->e->notice('Create table site_user failed'); - return false; - } - - return true; - } - - function down() { - $site = owa_coreAPI::entityFactory('base.site_user'); - $ret = $site->dropTable('site_user'); - return true; - } + + var $schema_version = 8; + + + function up($force = false) { + $site = owa_coreAPI::entityFactory('base.site_user'); + $ret = $site->createTable('site_user'); + if ($ret === false ) { + $this->e->notice('Create table site_user failed'); + return false; + } + + return true; + } + + function down() { + $site = owa_coreAPI::entityFactory('base.site_user'); + $ret = $site->dropTable('site_user'); + return true; + } } ?> \ No newline at end of file diff --git a/modules/base/updates/009.php b/modules/base/updates/009.php index 80ca9b600..13201d307 100644 --- a/modules/base/updates/009.php +++ b/modules/base/updates/009.php @@ -23,69 +23,69 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.5.0 + * @version $Revision$ + * @since owa 1.5.0 */ class owa_base_009_update extends owa_update { - - var $schema_version = 9; - - - function up($force = false) { - - //$handle = fopen(OWA_DIR . 'owa-config.php', 'r+'); - - $c = file_get_contents(OWA_DIR . 'owa-config.php'); - - $ret = copy(OWA_DIR . 'owa-config.php', OWA_DIR . 'owa-config.php.backup.' . time() ); - - if ($ret === false ) { - $this->e->notice('A backup of your owa-config.php could not be created. Check permissions to ensure your main OWA directory is writable.'); - return false; - } - - - if ($c) { - - $n0 = " + + var $schema_version = 9; + + + function up($force = false) { + + //$handle = fopen(OWA_DIR . 'owa-config.php', 'r+'); + + $c = file_get_contents(OWA_DIR . 'owa-config.php'); + + $ret = copy(OWA_DIR . 'owa-config.php', OWA_DIR . 'owa-config.php.backup.' . time() ); + + if ($ret === false ) { + $this->e->notice('A backup of your owa-config.php could not be created. Check permissions to ensure your main OWA directory is writable.'); + return false; + } + + + if ($c) { + + $n0 = " /** * AUTHENTICATION KEYS AND SALTS * * Change these to different unique phrases. */" . PHP_EOL.PHP_EOL; - $n1 = "define('OWA_NONCE_KEY', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL; - $n2 = "define('OWA_NONCE_SALT', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL; - $n3 = "define('OWA_AUTH_KEY', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL; - $n4 = "define('OWA_AUTH_SALT', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL . PHP_EOL; - $ne = "?>"; - - $value = $n0. $n1 . $n2 . $n3 . $n4 . $ne; - //fseek($handle, -1, SEEK_END); - //$ret = fwrite($handle, $value); - //fclose($handle); - $c = str_replace('?>', $value, $c); - - $ret = file_put_contents(OWA_DIR . 'owa-config.php', $c); - if ($ret === false ) { - $this->e->notice('owa-config.php could not be written to. Check permissions to ensure this file is writable.'); - return false; - } - $this->e->notice('Auth keys added to owa-config.php.'); - return true; - - } else { - $this->e->notice('owa-config.php could not be read. check permissions to ensure this file is readable.'); - return false; - } - - } - - function down() { - - return true; - } + $n1 = "define('OWA_NONCE_KEY', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL; + $n2 = "define('OWA_NONCE_SALT', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL; + $n3 = "define('OWA_AUTH_KEY', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL; + $n4 = "define('OWA_AUTH_SALT', '" . owa_coreAPI::secureRandomString(64) . "');" . PHP_EOL . PHP_EOL; + $ne = "?>"; + + $value = $n0. $n1 . $n2 . $n3 . $n4 . $ne; + //fseek($handle, -1, SEEK_END); + //$ret = fwrite($handle, $value); + //fclose($handle); + $c = str_replace('?>', $value, $c); + + $ret = file_put_contents(OWA_DIR . 'owa-config.php', $c); + if ($ret === false ) { + $this->e->notice('owa-config.php could not be written to. Check permissions to ensure this file is writable.'); + return false; + } + $this->e->notice('Auth keys added to owa-config.php.'); + return true; + + } else { + $this->e->notice('owa-config.php could not be read. check permissions to ensure this file is readable.'); + return false; + } + + } + + function down() { + + return true; + } } ?> \ No newline at end of file diff --git a/modules/base/updatesApply.php b/modules/base/updatesApply.php index e269dfecd..91f8e45e4 100644 --- a/modules/base/updatesApply.php +++ b/modules/base/updatesApply.php @@ -1,81 +1,81 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_updatesApplyController extends owa_controller { - - function action() { - - // fetch list of modules that require updates - $s = owa_coreAPI::serviceSingleton(); - - $modules = $s->getModulesNeedingUpdates(); - //print_r($modules); - //return; - - // foreach do update in order - - $error = false; - - foreach ($modules as $k => $v) { - - $ret = $s->modules[$v]->update(); - - if ($ret != true): - $error = true; - // if there is an error check to see if it's because the cli update mode is required - $cli_update_required = $s->modules[$v]->isCliUpdateModeRequired(); - break; - endif; - - } - - if ($error === true) { - - if($cli_update_required) { - $this->set('error_msg', $this->getMsg(3311)); - } else { - $this->set('error_msg', $this->getMsg(3307)); - } - - $this->setView('base.error'); - $this->setViewMethod('delegate'); - } else { - - // add data to container - $this->set('status_code', 3308); - $this->set('do', 'base.optionsGeneral'); - $this->setViewMethod('redirect'); - } - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_updatesApplyController extends owa_controller { + + function action() { + + // fetch list of modules that require updates + $s = owa_coreAPI::serviceSingleton(); + + $modules = $s->getModulesNeedingUpdates(); + //print_r($modules); + //return; + + // foreach do update in order + + $error = false; + + foreach ($modules as $k => $v) { + + $ret = $s->modules[$v]->update(); + + if ($ret != true): + $error = true; + // if there is an error check to see if it's because the cli update mode is required + $cli_update_required = $s->modules[$v]->isCliUpdateModeRequired(); + break; + endif; + + } + + if ($error === true) { + + if($cli_update_required) { + $this->set('error_msg', $this->getMsg(3311)); + } else { + $this->set('error_msg', $this->getMsg(3307)); + } + + $this->setView('base.error'); + $this->setViewMethod('delegate'); + } else { + + // add data to container + $this->set('status_code', 3308); + $this->set('do', 'base.optionsGeneral'); + $this->setViewMethod('redirect'); + } + } +} + ?> \ No newline at end of file diff --git a/modules/base/updatesApplyCli.php b/modules/base/updatesApplyCli.php index eebefcec4..460218fd3 100644 --- a/modules/base/updatesApplyCli.php +++ b/modules/base/updatesApplyCli.php @@ -1,130 +1,130 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_updatesApplyCliController extends owa_cliController { - - function __construct($params) { - define('OWA_UPDATING', true); - return parent::__construct($params); - } - - function action() { - - // fetch list of modules that require updates - $s = owa_coreAPI::serviceSingleton(); - - if ($this->isParam('listpending')) { - - return $this->listPendingUpdates(); - } - - if ($this->getParam('apply')) { - - return $this->apply($this->get('apply')); - } - - if ($this->getParam('rollback')) { - - return $this->rollback($this->get('rollback')); - } - - $modules = $s->getModulesNeedingUpdates(); - //print_r($modules); - //return; - - // foreach do update in order - if (!empty($modules)) { - $error = false; - - foreach ($modules as $k => $v) { - - $ret = $s->modules[$v]->update(); - - if ($ret != true): - $error = true; - break; - endif; - - } - - if ($error === true) { - owa_coreAPI::notice($this->getMsg(3307)); - } else { - - // add data to container - owa_coreAPI::notice($this->getMsg(3308)); - } - } else { - owa_coreAPI::notice("There are no modules with pending updates to apply."); - } - - - } - - function listPendingUpdates() { - - $s = owa_coreAPI::serviceSingleton(); - $modules = $s->getModulesNeedingUpdates(); - if ($modules) { - owa_coreAPI::notice(sprintf("Updates pending include: %s",print_r($modules, true))); - } else { - owa_coreAPI::notice("No updates are pending."); - } - } - - function apply($update) { - - list($module, $seq) = explode('.', $update); - $u = owa_coreAPI::updateFactory($module, $seq); - - // check for force command param - $force = false; - if ($this->isParam('--force')) { - - $force = true; - } - - $ret = $u->apply($force); - - if ($ret) { - owa_coreAPI::notice("Updates applied successfully."); - } - } - - function rollback($update) { - list($module, $seq) = explode('.', $update); - $u = owa_coreAPI::updateFactory($module, $seq); - $u->rollback(); - owa_coreAPI::notice("Rollback completed."); - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_updatesApplyCliController extends owa_cliController { + + function __construct($params) { + define('OWA_UPDATING', true); + return parent::__construct($params); + } + + function action() { + + // fetch list of modules that require updates + $s = owa_coreAPI::serviceSingleton(); + + if ($this->isParam('listpending')) { + + return $this->listPendingUpdates(); + } + + if ($this->getParam('apply')) { + + return $this->apply($this->get('apply')); + } + + if ($this->getParam('rollback')) { + + return $this->rollback($this->get('rollback')); + } + + $modules = $s->getModulesNeedingUpdates(); + //print_r($modules); + //return; + + // foreach do update in order + if (!empty($modules)) { + $error = false; + + foreach ($modules as $k => $v) { + + $ret = $s->modules[$v]->update(); + + if ($ret != true): + $error = true; + break; + endif; + + } + + if ($error === true) { + owa_coreAPI::notice($this->getMsg(3307)); + } else { + + // add data to container + owa_coreAPI::notice($this->getMsg(3308)); + } + } else { + owa_coreAPI::notice("There are no modules with pending updates to apply."); + } + + + } + + function listPendingUpdates() { + + $s = owa_coreAPI::serviceSingleton(); + $modules = $s->getModulesNeedingUpdates(); + if ($modules) { + owa_coreAPI::notice(sprintf("Updates pending include: %s",print_r($modules, true))); + } else { + owa_coreAPI::notice("No updates are pending."); + } + } + + function apply($update) { + + list($module, $seq) = explode('.', $update); + $u = owa_coreAPI::updateFactory($module, $seq); + + // check for force command param + $force = false; + if ($this->isParam('--force')) { + + $force = true; + } + + $ret = $u->apply($force); + + if ($ret) { + owa_coreAPI::notice("Updates applied successfully."); + } + } + + function rollback($update) { + list($module, $seq) = explode('.', $update); + $u = owa_coreAPI::updateFactory($module, $seq); + $u->rollback(); + owa_coreAPI::notice("Rollback completed."); + } + +} + ?> \ No newline at end of file diff --git a/modules/base/users.php b/modules/base/users.php index 327c77eec..7498691ca 100644 --- a/modules/base/users.php +++ b/modules/base/users.php @@ -1,78 +1,78 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_usersController extends owa_adminController { - - function __construct($params) { - - $this->setRequiredCapability('edit_users'); - return parent::__construct($params); - } - - function action() { - - $db = owa_coreAPI::dbSingleton(); - $db->selectFrom('owa_user'); - $db->selectColumn("*"); - $users = $db->getAllRows(); - $this->set('users', $users); - $this->setView('base.options'); - $this->setSubview('base.users'); - } -} - - -/** - * Users Roster View - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_usersView extends owa_view { - - function render() { - - //page title - $this->t->set('page_title', 'User Roster'); - $this->body->set_template('users.tpl'); - $this->body->set('headline', 'User Roster'); - $this->body->set('users', $this->get('users')); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_usersController extends owa_adminController { + + function __construct($params) { + + $this->setRequiredCapability('edit_users'); + return parent::__construct($params); + } + + function action() { + + $db = owa_coreAPI::dbSingleton(); + $db->selectFrom('owa_user'); + $db->selectColumn("*"); + $users = $db->getAllRows(); + $this->set('users', $users); + $this->setView('base.options'); + $this->setSubview('base.users'); + } +} + + +/** + * Users Roster View + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_usersView extends owa_view { + + function render() { + + //page title + $this->t->set('page_title', 'User Roster'); + $this->body->set_template('users.tpl'); + $this->body->set('headline', 'User Roster'); + $this->body->set('users', $this->get('users')); + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersAdd.php b/modules/base/usersAdd.php index 84cee64bc..1fc2bac18 100644 --- a/modules/base/usersAdd.php +++ b/modules/base/usersAdd.php @@ -1,95 +1,95 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersAddController extends owa_adminController { - - function __construct($params) { - - parent::__construct($params); - - $this->setRequiredCapability('edit_users'); - $this->setNonceRequired(); - - // Check for user with the same email address - // this is needed or else the change password feature will not know which account - // to chane the password for. - $v1 = owa_coreAPI::validationFactory('entityDoesNotExist'); - $v1->setConfig('entity', 'base.user'); - $v1->setConfig('column', 'email_address'); - $v1->setValues(trim($this->getParam('email_address'))); - $v1->setErrorMessage($this->getMsg(3009)); - $this->setValidation('email_address', $v1); - - // Check user name. - $v2 = owa_coreAPI::validationFactory('entityDoesNotExist'); - $v2->setConfig('entity', 'base.user'); - $v2->setConfig('column', 'user_id'); - $v2->setValues(trim($this->getParam('user_id'))); - $v2->setErrorMessage($this->getMsg(3001)); - $this->setValidation('user_id', $v2); - } - - function action() { - - $userManager = owa_coreApi::supportClassFactory('base', 'userManager'); - - - $user_params = array( 'user_id' => trim($this->params['user_id']), - 'real_name' => $this->params['real_name'], - 'role' => $this->params['role'], - 'email_address' => trim($this->params['email_address'])); - - $temp_passkey = $userManager->createNewUser($user_params); - - // log account creation event to event queue - $ed = owa_coreAPI::getEventDispatch(); - $ed->log(array( 'user_id' => $this->params['user_id'], - 'real_name' => $this->params['real_name'], - 'role' => $this->params['role'], - 'email_address' => $this->params['email_address'], - 'temp_passkey' => $temp_passkey), - 'base.new_user_account'); - - $this->setRedirectAction('base.users'); - $this->set('status_code', 3000); - } - - function errorAction() { - $this->setView('base.options'); - $this->setSubview('base.usersProfile'); - $this->set('error_code', 3009); - //assign original form data so the user does not have to re-enter the data - $this->set('profile', $this->params); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersAddController extends owa_adminController { + + function __construct($params) { + + parent::__construct($params); + + $this->setRequiredCapability('edit_users'); + $this->setNonceRequired(); + + // Check for user with the same email address + // this is needed or else the change password feature will not know which account + // to chane the password for. + $v1 = owa_coreAPI::validationFactory('entityDoesNotExist'); + $v1->setConfig('entity', 'base.user'); + $v1->setConfig('column', 'email_address'); + $v1->setValues(trim($this->getParam('email_address'))); + $v1->setErrorMessage($this->getMsg(3009)); + $this->setValidation('email_address', $v1); + + // Check user name. + $v2 = owa_coreAPI::validationFactory('entityDoesNotExist'); + $v2->setConfig('entity', 'base.user'); + $v2->setConfig('column', 'user_id'); + $v2->setValues(trim($this->getParam('user_id'))); + $v2->setErrorMessage($this->getMsg(3001)); + $this->setValidation('user_id', $v2); + } + + function action() { + + $userManager = owa_coreApi::supportClassFactory('base', 'userManager'); + + + $user_params = array( 'user_id' => trim($this->params['user_id']), + 'real_name' => $this->params['real_name'], + 'role' => $this->params['role'], + 'email_address' => trim($this->params['email_address'])); + + $temp_passkey = $userManager->createNewUser($user_params); + + // log account creation event to event queue + $ed = owa_coreAPI::getEventDispatch(); + $ed->log(array( 'user_id' => $this->params['user_id'], + 'real_name' => $this->params['real_name'], + 'role' => $this->params['role'], + 'email_address' => $this->params['email_address'], + 'temp_passkey' => $temp_passkey), + 'base.new_user_account'); + + $this->setRedirectAction('base.users'); + $this->set('status_code', 3000); + } + + function errorAction() { + $this->setView('base.options'); + $this->setSubview('base.usersProfile'); + $this->set('error_code', 3009); + //assign original form data so the user does not have to re-enter the data + $this->set('profile', $this->params); + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersChangePassword.php b/modules/base/usersChangePassword.php index a7ab2ea93..8259d0775 100644 --- a/modules/base/usersChangePassword.php +++ b/modules/base/usersChangePassword.php @@ -1,90 +1,90 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersChangePasswordController extends owa_controller { - - /** - * @var owa_userManager - */ - private $_userManager; - - function __construct($params) { - - parent::__construct($params); - - // Add validations to the run - $v1 = owa_coreAPI::validationFactory('stringMatch'); - $v1->setValues(array($this->getParam('password'), $this->getParam('password2'))); - $v1->setErrorMessage("Your passwords must match."); - $this->setValidation('password_match', $v1); - - $this->_userManager = owa_coreApi::supportClassFactory('base', 'userManager'); - $rules = $this->_userManager->getPasswordValidationRules($this->getParam('password')); - - foreach ($rules as $key => $rule) { - $this->setValidation($key, $rule); - } - - return; - } - - function action() { - - $auth = &owa_auth::get_instance(); - $status = $auth->authenticateUserTempPasskey($this->params['k']); - - // log to event queue - if ($status === true) { - $ed = owa_coreAPI::getEventDispatch(); - $new_password = array('key' => $this->params['k'], 'password' => $this->params['password'], 'ip' => $_SERVER['REMOTE_ADDR']); - $ed->log($new_password, 'base.set_password'); - $auth->deleteCredentials(); - $this->setRedirectAction('base.loginForm'); - $this->set('status_code', 3006); - } else { - $this->setRedirectAction('base.loginForm'); - $this->set('error_code', 2011); // can't find key in the db - } - } - - function errorAction() { - - $this->setView('base.usersPasswordEntry'); - $this->set('k', $this->getParam('k')); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersChangePasswordController extends owa_controller { + + /** + * @var owa_userManager + */ + private $_userManager; + + function __construct($params) { + + parent::__construct($params); + + // Add validations to the run + $v1 = owa_coreAPI::validationFactory('stringMatch'); + $v1->setValues(array($this->getParam('password'), $this->getParam('password2'))); + $v1->setErrorMessage("Your passwords must match."); + $this->setValidation('password_match', $v1); + + $this->_userManager = owa_coreApi::supportClassFactory('base', 'userManager'); + $rules = $this->_userManager->getPasswordValidationRules($this->getParam('password')); + + foreach ($rules as $key => $rule) { + $this->setValidation($key, $rule); + } + + return; + } + + function action() { + + $auth = &owa_auth::get_instance(); + $status = $auth->authenticateUserTempPasskey($this->params['k']); + + // log to event queue + if ($status === true) { + $ed = owa_coreAPI::getEventDispatch(); + $new_password = array('key' => $this->params['k'], 'password' => $this->params['password'], 'ip' => $_SERVER['REMOTE_ADDR']); + $ed->log($new_password, 'base.set_password'); + $auth->deleteCredentials(); + $this->setRedirectAction('base.loginForm'); + $this->set('status_code', 3006); + } else { + $this->setRedirectAction('base.loginForm'); + $this->set('error_code', 2011); // can't find key in the db + } + } + + function errorAction() { + + $this->setView('base.usersPasswordEntry'); + $this->set('k', $this->getParam('k')); + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersDelete.php b/modules/base/usersDelete.php index 32db4e730..974dfe070 100644 --- a/modules/base/usersDelete.php +++ b/modules/base/usersDelete.php @@ -1,54 +1,54 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersDeleteController extends owa_adminController { - - function __construct($params) { - - $this->setRequiredCapability('edit_users'); - $this->setNonceRequired(); - return parent::__construct($params); - } - - function action() { - - $userManager = owa_coreApi::supportClassFactory('base', 'userManager'); - - // add check here to ensure that this is not the default user.... - $userManager->deleteUser($this->getParam('user_id')); - - $this->setRedirectAction('base.users'); - $this->set('status_code', 3004); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersDeleteController extends owa_adminController { + + function __construct($params) { + + $this->setRequiredCapability('edit_users'); + $this->setNonceRequired(); + return parent::__construct($params); + } + + function action() { + + $userManager = owa_coreApi::supportClassFactory('base', 'userManager'); + + // add check here to ensure that this is not the default user.... + $userManager->deleteUser($this->getParam('user_id')); + + $this->setRedirectAction('base.users'); + $this->set('status_code', 3004); + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersEdit.php b/modules/base/usersEdit.php index caa625bb7..0511a5dbe 100644 --- a/modules/base/usersEdit.php +++ b/modules/base/usersEdit.php @@ -1,87 +1,87 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersEditController extends owa_adminController { - - function __construct($params) { - - parent::__construct($params); - - $this->setRequiredCapability('edit_users'); - $this->setNonceRequired(); - - // check that user_id is present - $v1 = owa_coreAPI::validationFactory('required'); - $v1->setValues($this->getParam('user_id')); - $this->setValidation('user_id', $v1); - - // Check user name exists - $v2 = owa_coreAPI::validationFactory('entityExists'); - $v2->setConfig('entity', 'base.user'); - $v2->setConfig('column', 'user_id'); - $v2->setValues($this->getParam('user_id')); - $v2->setErrorMessage($this->getMsg(3001)); - $this->setValidation('user_id', $v2); - } - - function action() { - - // This needs form validation in a bad way. - - $u = owa_coreAPI::entityFactory('base.user'); - $u->getByColumn('user_id', $this->getParam('user_id')); - $u->set('email_address', $this->getParam('email_address')); - - // never change the role of the admin user - if (!$u->isOWAAdmin()) { - $u->set('real_name', $this->getParam('real_name')); - $u->set('role', $this->getParam('role')); - } - - - $u->update(); - $this->set('status_code', 3003); - $this->setRedirectAction('base.users'); - } - - function errorAction() { - - $this->setView('base.options'); - $this->setSubview('base.usersProfile'); - $this->set('error_code', 3311); - $this->set('user', $this->params); - } - -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersEditController extends owa_adminController { + + function __construct($params) { + + parent::__construct($params); + + $this->setRequiredCapability('edit_users'); + $this->setNonceRequired(); + + // check that user_id is present + $v1 = owa_coreAPI::validationFactory('required'); + $v1->setValues($this->getParam('user_id')); + $this->setValidation('user_id', $v1); + + // Check user name exists + $v2 = owa_coreAPI::validationFactory('entityExists'); + $v2->setConfig('entity', 'base.user'); + $v2->setConfig('column', 'user_id'); + $v2->setValues($this->getParam('user_id')); + $v2->setErrorMessage($this->getMsg(3001)); + $this->setValidation('user_id', $v2); + } + + function action() { + + // This needs form validation in a bad way. + + $u = owa_coreAPI::entityFactory('base.user'); + $u->getByColumn('user_id', $this->getParam('user_id')); + $u->set('email_address', $this->getParam('email_address')); + + // never change the role of the admin user + if (!$u->isOWAAdmin()) { + $u->set('real_name', $this->getParam('real_name')); + $u->set('role', $this->getParam('role')); + } + + + $u->update(); + $this->set('status_code', 3003); + $this->setRedirectAction('base.users'); + } + + function errorAction() { + + $this->setView('base.options'); + $this->setSubview('base.usersProfile'); + $this->set('error_code', 3311); + $this->set('user', $this->params); + } + +} + + ?> \ No newline at end of file diff --git a/modules/base/usersNewAccount.php b/modules/base/usersNewAccount.php index 98aa53121..f550a52af 100644 --- a/modules/base/usersNewAccount.php +++ b/modules/base/usersNewAccount.php @@ -1,91 +1,91 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersNewAccountController extends owa_controller { - - function __construct($params) { - return parent::__construct($params); - - } - - function action() { - - $event = $this->getParam('event'); - - // return email view - $data['user_id']= $event->get('user_id'); - $data['email_address']= $event->get('email_address'); - $data['temp_passkey'] = $event->get('temp_passkey'); - $data['subject'] = 'OWA User Account Setup'; - $data['view'] = 'base.usersNewAccount'; - $data['view_method'] = 'email'; - - return $data; - } - -} - - -/** - * New Account Notification View - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersNewAccountView extends owa_mailView { - - function __construct() { - - return parent::__construct(); - } - - function render($data) { - - $this->t->set_template('wrapper_email.tpl'); - $this->body->set_template('users_new_account_email.tpl'); - $this->body->set('user_id', $data['user_id']); - $this->body->set('key', $data['temp_passkey']); - // mailer specific - $this->setMailSubject($data['subject']); - $this->addMailToAddress($data['email_address'], @$data['name']); - - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersNewAccountController extends owa_controller { + + function __construct($params) { + return parent::__construct($params); + + } + + function action() { + + $event = $this->getParam('event'); + + // return email view + $data['user_id']= $event->get('user_id'); + $data['email_address']= $event->get('email_address'); + $data['temp_passkey'] = $event->get('temp_passkey'); + $data['subject'] = 'OWA User Account Setup'; + $data['view'] = 'base.usersNewAccount'; + $data['view_method'] = 'email'; + + return $data; + } + +} + + +/** + * New Account Notification View + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersNewAccountView extends owa_mailView { + + function __construct() { + + return parent::__construct(); + } + + function render($data) { + + $this->t->set_template('wrapper_email.tpl'); + $this->body->set_template('users_new_account_email.tpl'); + $this->body->set('user_id', $data['user_id']); + $this->body->set('key', $data['temp_passkey']); + // mailer specific + $this->setMailSubject($data['subject']); + $this->addMailToAddress($data['email_address'], @$data['name']); + + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersPasswordEntry.php b/modules/base/usersPasswordEntry.php index 3b53805c3..de584079f 100644 --- a/modules/base/usersPasswordEntry.php +++ b/modules/base/usersPasswordEntry.php @@ -1,83 +1,83 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersPasswordEntryController extends owa_controller { - - function __construct($params) { - - return parent::__construct($params); - } - - function action() { - - $this->set('key', $this->getParam('k')); - $this->setView('base.usersPasswordEntry'); - return; - } - - -} - -/** - * Change Password View - * - * Presents a simple form to the user asking them to enter a new password. - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersPasswordEntryView extends owa_view { - - function __construct() { - - return parent::__construct(); - } - - function render($data) { - - $this->t->set_template('wrapper_public.tpl'); - $this->body->set_template('users_change_password.tpl'); - $this->body->set('headline', $this->getMsg(3005)); - $this->body->set('key', $this->get('key')); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersPasswordEntryController extends owa_controller { + + function __construct($params) { + + return parent::__construct($params); + } + + function action() { + + $this->set('key', $this->getParam('k')); + $this->setView('base.usersPasswordEntry'); + return; + } + + +} + +/** + * Change Password View + * + * Presents a simple form to the user asking them to enter a new password. + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersPasswordEntryView extends owa_view { + + function __construct() { + + return parent::__construct(); + } + + function render($data) { + + $this->t->set_template('wrapper_public.tpl'); + $this->body->set_template('users_change_password.tpl'); + $this->body->set('headline', $this->getMsg(3005)); + $this->body->set('key', $this->get('key')); + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersProfile.php b/modules/base/usersProfile.php index 2820702f2..5aa3287bd 100644 --- a/modules/base/usersProfile.php +++ b/modules/base/usersProfile.php @@ -1,109 +1,109 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersProfileController extends owa_controller { - - function __construct($params) { - - $this->setRequiredCapability('edit_users'); - return parent::__construct($params); - } - - function action() { - - // This needs form validation in a bad way. - //Check to see if user is passed by constructor or else fetch the object. - if ($this->getParam('user_id')) { - $u = owa_coreAPI::entityFactory('base.user'); - $u->getByColumn('user_id', $this->getParam('user_id')); - $this->set('profile', $u->_getProperties()); - $this->set('edit', true); - $this->set('user_id', $this->getParam('user_id')); - } else { - $this->set('edit', false); - $this->set('profile', array()); - } - - $this->setView('base.options'); - $this->setSubview('base.usersProfile'); - - } - -} - -/** - * OWA User Profile View - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersProfileView extends owa_view { - - function __construct() { - - return parent::__construct(); - } - - function render($data) { - $user = $this->get('profile'); - $this->body->set('isAdmin', false); - - if ($this->get('edit')) { - $this->body->set('headline', 'Edit user profile'); - $this->body->set('action', 'base.usersEdit'); - $this->body->set('edit', true); - $userEntity = owa_coreAPI::entityFactory( 'base.user' ); - $userEntity->load( $user['id'] ); - $this->body->set('isAdmin', $userEntity->isOWAAdmin()); - } else { - $this->body->set('headline', 'Add a new user profile'); - $this->body->set('action', 'base.usersAdd'); - $this->body->set('edit', false); - } - //page title - $this->t->set('page_title', 'User Profile'); - $this->body->set_template('users_addoredit.tpl'); - $this->body->set('roles', owa_coreAPI::getAllRoles()); - - $this->body->set('user', $user); - - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersProfileController extends owa_controller { + + function __construct($params) { + + $this->setRequiredCapability('edit_users'); + return parent::__construct($params); + } + + function action() { + + // This needs form validation in a bad way. + //Check to see if user is passed by constructor or else fetch the object. + if ($this->getParam('user_id')) { + $u = owa_coreAPI::entityFactory('base.user'); + $u->getByColumn('user_id', $this->getParam('user_id')); + $this->set('profile', $u->_getProperties()); + $this->set('edit', true); + $this->set('user_id', $this->getParam('user_id')); + } else { + $this->set('edit', false); + $this->set('profile', array()); + } + + $this->setView('base.options'); + $this->setSubview('base.usersProfile'); + + } + +} + +/** + * OWA User Profile View + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersProfileView extends owa_view { + + function __construct() { + + return parent::__construct(); + } + + function render($data) { + $user = $this->get('profile'); + $this->body->set('isAdmin', false); + + if ($this->get('edit')) { + $this->body->set('headline', 'Edit user profile'); + $this->body->set('action', 'base.usersEdit'); + $this->body->set('edit', true); + $userEntity = owa_coreAPI::entityFactory( 'base.user' ); + $userEntity->load( $user['id'] ); + $this->body->set('isAdmin', $userEntity->isOWAAdmin()); + } else { + $this->body->set('headline', 'Add a new user profile'); + $this->body->set('action', 'base.usersAdd'); + $this->body->set('edit', false); + } + //page title + $this->t->set('page_title', 'User Profile'); + $this->body->set_template('users_addoredit.tpl'); + $this->body->set('roles', owa_coreAPI::getAllRoles()); + + $this->body->set('user', $user); + + } +} + ?> \ No newline at end of file diff --git a/modules/base/usersResetPassword.php b/modules/base/usersResetPassword.php index fd889e5b6..b3ed2ac7f 100644 --- a/modules/base/usersResetPassword.php +++ b/modules/base/usersResetPassword.php @@ -1,92 +1,92 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersResetPasswordController extends owa_controller { - - function __construct($params) { - - return parent::__construct($params); - } - - function action() { - - $event = $this->getParam('event'); - - $auth = owa_auth::get_instance(); - $u = owa_coreAPI::entityFactory('base.user'); - $u->getByColumn('email_address', $event->get('email_address')); - $u->set('temp_passkey', $auth->generateTempPasskey($u->get('user_id'))); - $status = $u->update(); - $this->e->debug('status: '.$status); - - if ($status === true) { - - $this->setView( 'base.usersResetPassword' ); - $this->set( 'key', $u->get('temp_passkey' ) ); - $this->set( 'email_address', $u->get('email_address' ) ); - - } else { - - $this->e->debug( "could not update password in db." ); - } - } - -} - -/** - * Reset Password Notification View - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersResetPasswordView extends owa_mailView { - - function render($data) { - - $this->t->set_template('wrapper_email.tpl'); - $this->body->set_template('users_reset_password_email.tpl'); - $this->body->set('key', $this->get('key')); - $this->setMailSubject('Your New OWA Password'); - $this->addMailToAddress($this->get('email_address')); - } -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersResetPasswordController extends owa_controller { + + function __construct($params) { + + return parent::__construct($params); + } + + function action() { + + $event = $this->getParam('event'); + + $auth = owa_auth::get_instance(); + $u = owa_coreAPI::entityFactory('base.user'); + $u->getByColumn('email_address', $event->get('email_address')); + $u->set('temp_passkey', $auth->generateTempPasskey($u->get('user_id'))); + $status = $u->update(); + $this->e->debug('status: '.$status); + + if ($status === true) { + + $this->setView( 'base.usersResetPassword' ); + $this->set( 'key', $u->get('temp_passkey' ) ); + $this->set( 'email_address', $u->get('email_address' ) ); + + } else { + + $this->e->debug( "could not update password in db." ); + } + } + +} + +/** + * Reset Password Notification View + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersResetPasswordView extends owa_mailView { + + function render($data) { + + $this->t->set_template('wrapper_email.tpl'); + $this->body->set_template('users_reset_password_email.tpl'); + $this->body->set('key', $this->get('key')); + $this->setMailSubject('Your New OWA Password'); + $this->addMailToAddress($this->get('email_address')); + } +} + + ?> \ No newline at end of file diff --git a/modules/base/usersSetPassword.php b/modules/base/usersSetPassword.php index 26fe73c4f..faa0222e6 100644 --- a/modules/base/usersSetPassword.php +++ b/modules/base/usersSetPassword.php @@ -1,95 +1,95 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersSetPasswordController extends owa_controller { - - function __construct($params) { - - return parent::__construct($params); - } - - function action() { - - $event = $this->getParam('event'); - - /** - * @var $userManager owa_userManager - */ - $userManager = owa_coreApi::supportClassFactory('base', 'userManager'); - $u = $userManager->updateUserPassword([ - 'temp_passkey' => $event->get('key'), - 'password' => $event->get('password'), - ]); - - if ($u !== false) { - $data['view'] = 'base.usersSetPassword'; - $data['view_method'] = 'email'; - $data['ip'] = $event->get('ip'); - $data['subject'] = 'Password Change Complete'; - $data['email_address'] = $u->get('email_address'); - } - - return $data; - } - -} - -/** - * Set Password Notification View - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_usersSetPasswordView extends owa_view { - - function __construct() { - - return parent::__construct(); - } - - function render($data) { - - $this->t->set_template('wrapper_email.tpl'); - $this->body->set_template('users_set_password_email.tpl'); - $this->body->set('ip', $data['ip']); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersSetPasswordController extends owa_controller { + + function __construct($params) { + + return parent::__construct($params); + } + + function action() { + + $event = $this->getParam('event'); + + /** + * @var $userManager owa_userManager + */ + $userManager = owa_coreApi::supportClassFactory('base', 'userManager'); + $u = $userManager->updateUserPassword([ + 'temp_passkey' => $event->get('key'), + 'password' => $event->get('password'), + ]); + + if ($u !== false) { + $data['view'] = 'base.usersSetPassword'; + $data['view_method'] = 'email'; + $data['ip'] = $event->get('ip'); + $data['subject'] = 'Password Change Complete'; + $data['email_address'] = $u->get('email_address'); + } + + return $data; + } + +} + +/** + * Set Password Notification View + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_usersSetPasswordView extends owa_view { + + function __construct() { + + return parent::__construct(); + } + + function render($data) { + + $this->t->set_template('wrapper_email.tpl'); + $this->body->set_template('users_set_password_email.tpl'); + $this->body->set('ip', $data['ip']); + } +} + ?> \ No newline at end of file diff --git a/modules/base/widgetOwaNews.php b/modules/base/widgetOwaNews.php index a8cfb8b16..753c2fa02 100644 --- a/modules/base/widgetOwaNews.php +++ b/modules/base/widgetOwaNews.php @@ -1,69 +1,69 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_widgetOwaNewsController extends owa_widgetController { - - function __construct($params) { - - return parent::__construct($params); - } - - function action() { - - $this->set('title', 'OWA News'); - - //$data['params'] = $this->params; - - //Fetch latest OWA news - $crawler = new owa_http(); - $response = $crawler->getRequest($this->config['owa_news_url']); - - $news = json_decode($response); - - $this->set('news', $news); - $this->setView('base.widgetOwaNews'); - } - -} - -class owa_widgetOwaNewsView extends owa_view { - - function render($data) { - - $this->t->set_template('wrapper_blank.tpl'); - $this->body->set_template('news.tpl'); - $this->body->set('news', $data['news']); - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_widgetOwaNewsController extends owa_widgetController { + + function __construct($params) { + + return parent::__construct($params); + } + + function action() { + + $this->set('title', 'OWA News'); + + //$data['params'] = $this->params; + + //Fetch latest OWA news + $crawler = new owa_http(); + $response = $crawler->getRequest($this->config['owa_news_url']); + + $news = json_decode($response); + + $this->set('news', $news); + $this->setView('base.widgetOwaNews'); + } + +} + +class owa_widgetOwaNewsView extends owa_view { + + function render($data) { + + $this->t->set_template('wrapper_blank.tpl'); + $this->body->set_template('news.tpl'); + $this->body->set('news', $data['news']); + } + +} + ?> \ No newline at end of file diff --git a/modules/base/xmlVisitsGeolocation.php b/modules/base/xmlVisitsGeolocation.php index 8f24e56fb..d21c05835 100644 --- a/modules/base/xmlVisitsGeolocation.php +++ b/modules/base/xmlVisitsGeolocation.php @@ -1,135 +1,135 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_xmlVisitsGeolocationController extends owa_reportController { - - function owa_xmlVisitsGeolocationController($params) { - - return owa_xmlVisitsGeolocationController::__construct($params); - } - - function __construct($params) { - - return parent::__construct($params); - } - - function action() { - - $site_id = $this->getParam('site_id'); - if ($site_id): - //get site labels - $s = owa_coreAPI::entityFactory('base.site'); - $s->getByColumn('site_id', $site_id); - $this->set('site_name', $s->get('name')); - $this->set('site_description', $s->get('description')); - else: - $this->set('site_name', 'All Sites'); - $this->set('site_description', 'All Sites Tracked by OWA'); - endif; - - //setup Metrics - $m = owa_coreApi::metricFactory('base.latestVisits'); - $m->setConstraint('site_id', $this->getParam('site_id')); - //$period = $this->makeTimePeriod('all_time'); - $m->setPeriod($this->getPeriod()); - $m->setLimit(100); - $m->setOrder('DESC'); - $this->set('latest_visits', $m->generate()); - $this->setView('base.xmlVisitsGeolocation'); - - return; - - } - -} - - - -/** - * Visits Geolocation xml View - * - * @author Peter Adams - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_xmlVisitsGeolocationView extends owa_view { - - function owa_xmlVisitsGeolocationView() { - - return owa_xmlVisitsGeolocationView::__construct(); - } - - function __construct() { - - return parent::__construct(); - } - - function render($data) { - - $this->t->set_template('wrapper_blank.tpl'); - - // load body template - $this->body->set_template('xml_visits_geolocation.tpl'); - //$this->body->set_template('kml_google_sample.tpl'); - $this->body->set('visits', $this->get('latest_visits')); - $this->body->set('site_name', $this->get('site_name')); - $this->body->set('site_domain', $this->get('site_domain')); - $this->body->set('site_description', $this->get('site_description')); - $this->body->set('xml', trim('')); - $this->_setLinkState(); - - //if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')): - // ob_start("ob_gzhandler"); - // header('Content-type: text/xml', true); - // ob_end_flush(); - //else: - //header('Content-type: text/xml', true); - header('Content-type: application/vnd.google-earth.kml+xml; charset=UTF-8', true); - //endif: - - return; - } - - -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_xmlVisitsGeolocationController extends owa_reportController { + + function owa_xmlVisitsGeolocationController($params) { + + return owa_xmlVisitsGeolocationController::__construct($params); + } + + function __construct($params) { + + return parent::__construct($params); + } + + function action() { + + $site_id = $this->getParam('site_id'); + if ($site_id): + //get site labels + $s = owa_coreAPI::entityFactory('base.site'); + $s->getByColumn('site_id', $site_id); + $this->set('site_name', $s->get('name')); + $this->set('site_description', $s->get('description')); + else: + $this->set('site_name', 'All Sites'); + $this->set('site_description', 'All Sites Tracked by OWA'); + endif; + + //setup Metrics + $m = owa_coreApi::metricFactory('base.latestVisits'); + $m->setConstraint('site_id', $this->getParam('site_id')); + //$period = $this->makeTimePeriod('all_time'); + $m->setPeriod($this->getPeriod()); + $m->setLimit(100); + $m->setOrder('DESC'); + $this->set('latest_visits', $m->generate()); + $this->setView('base.xmlVisitsGeolocation'); + + return; + + } + +} + + + +/** + * Visits Geolocation xml View + * + * @author Peter Adams + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_xmlVisitsGeolocationView extends owa_view { + + function owa_xmlVisitsGeolocationView() { + + return owa_xmlVisitsGeolocationView::__construct(); + } + + function __construct() { + + return parent::__construct(); + } + + function render($data) { + + $this->t->set_template('wrapper_blank.tpl'); + + // load body template + $this->body->set_template('xml_visits_geolocation.tpl'); + //$this->body->set_template('kml_google_sample.tpl'); + $this->body->set('visits', $this->get('latest_visits')); + $this->body->set('site_name', $this->get('site_name')); + $this->body->set('site_domain', $this->get('site_domain')); + $this->body->set('site_description', $this->get('site_description')); + $this->body->set('xml', trim('')); + $this->_setLinkState(); + + //if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')): + // ob_start("ob_gzhandler"); + // header('Content-type: text/xml', true); + // ob_end_flush(); + //else: + //header('Content-type: text/xml', true); + header('Content-type: application/vnd.google-earth.kml+xml; charset=UTF-8', true); + //endif: + + return; + } + + +} + + ?> \ No newline at end of file diff --git a/modules/domstream/handlers/domstreamHandlers.php b/modules/domstream/handlers/domstreamHandlers.php index 6a6d2f569..3aa777e47 100644 --- a/modules/domstream/handlers/domstreamHandlers.php +++ b/modules/domstream/handlers/domstreamHandlers.php @@ -1,82 +1,82 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.2.1 - */ - -class owa_domstreamHandlers extends owa_observer { - - /** - * Notify method - * - * @param object $event - * @access public - */ - function notify($event) { - - $ds = owa_coreAPI::entityFactory('base.domstream'); - $ds->load( $event->get('guid') ); - - if ( ! $ds->wasPersisted() ) { - - $ds->setProperties( $event->getProperties() ); - - $ds->set( 'id', $event->get( 'guid' ) ); - $ds->set( 'domstream_guid', $event->get('domstream_guid') ); - $ds->set( 'document_id', $ds->generateId( $event->get('page_url') ) ); - $ds->set( 'page_url', $event->get('page_url') ); - $ds->set( 'events', $event->get('stream_events') ); - $ds->set( 'duration', $event->get('duration') ); - - $ret = $ds->create(); - - if ( $ret ) { - - // Tell others that "dom.stream" has been logged - $eq = owa_coreAPI::getEventDispatch(); - $nevent = $eq->makeEvent($event->getEventType().'_logged'); - $nevent->setProperties($event->getProperties()); - $eq->asyncNotify($nevent); - - return OWA_EHS_EVENT_HANDLED; - } else { - return OWA_EHS_EVENT_FAILED; - } - - } else { - owa_coreAPI::debug('No persisting. Domsteam already exists.'); - return OWA_EHS_EVENT_HANDLED; - } - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.2.1 + */ + +class owa_domstreamHandlers extends owa_observer { + + /** + * Notify method + * + * @param object $event + * @access public + */ + function notify($event) { + + $ds = owa_coreAPI::entityFactory('base.domstream'); + $ds->load( $event->get('guid') ); + + if ( ! $ds->wasPersisted() ) { + + $ds->setProperties( $event->getProperties() ); + + $ds->set( 'id', $event->get( 'guid' ) ); + $ds->set( 'domstream_guid', $event->get('domstream_guid') ); + $ds->set( 'document_id', $ds->generateId( $event->get('page_url') ) ); + $ds->set( 'page_url', $event->get('page_url') ); + $ds->set( 'events', $event->get('stream_events') ); + $ds->set( 'duration', $event->get('duration') ); + + $ret = $ds->create(); + + if ( $ret ) { + + // Tell others that "dom.stream" has been logged + $eq = owa_coreAPI::getEventDispatch(); + $nevent = $eq->makeEvent($event->getEventType().'_logged'); + $nevent->setProperties($event->getProperties()); + $eq->asyncNotify($nevent); + + return OWA_EHS_EVENT_HANDLED; + } else { + return OWA_EHS_EVENT_FAILED; + } + + } else { + owa_coreAPI::debug('No persisting. Domsteam already exists.'); + return OWA_EHS_EVENT_HANDLED; + } + } + +} + ?> \ No newline at end of file diff --git a/modules/domstream/module.php b/modules/domstream/module.php index 856c5f12a..58c165d5e 100644 --- a/modules/domstream/module.php +++ b/modules/domstream/module.php @@ -26,209 +26,209 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.6.1 + * @version $Revision$ + * @since owa 1.6.1 */ class owa_domstreamModule extends owa_module { - - function __construct() { - - $this->name = 'domstream'; - $this->display_name = 'Domstream'; - $this->group = 'logging'; - $this->author = 'Peter Adams'; - $this->version = '1.0'; - $this->description = 'Logs the users mouse and other DOM movements.'; - $this->config_required = false; - $this->required_schema_version = 1; - - // register named queues - - return parent::__construct(); - } - - function registerFilters() { - - // adds tracking cmd to js tracker. - if ( owa_coreAPI::getSetting( 'domstream', 'is_active' ) ) { - - $this->registerFilter('tracker_tag_cmds', $this, 'addToTracker', 99); - } - } - - /** - * Adds domstream logging to the JS tracker tag. - * @return array - */ - function addToTracker( $cmds ) { - - $cmds[] = "owa_cmds.push(['trackDomStream']);"; - - return $cmds; - } - - /** - * Registers Event Handlers with queue queue - * - */ - function _registerEventHandlers() { - - $this->registerEventHandler('dom.stream', 'domstreamHandlers'); - } - - /** - * Registers Reports in Main Navigation - * - */ - function registerNavigation() { - - $this->addNavigationLinkInSubGroup( 'Content', 'base.reportDomstreams', 'Domstreams', 5); - } - - /** - * Register API methods - * - */ - function registerApiMethods() { - - $this->registerApiMethod('getDomstreams', - array( $this, 'getDomstreams' ), - array( - 'startDate', - 'endDate', - 'document_id', - 'siteId', - 'resultsPerPage', - 'page', - 'format' ), - '', - 'view_reports' - ); - - $this->registerApiMethod('getDomstream', - array($this, 'getDomstream'), - array('domstream_guid'), - '', - 'view_reports' - ); - } - - // api method callback - function getDomstreams($start_date, $end_date, $document_id = '', $siteId = '', $resultsPerPage = 20, $page = 1, $format = '') { - - $rs = owa_coreAPI::supportClassFactory('base', 'paginatedResultSet'); - $db = owa_coreAPI::dbSingleton(); - $db->selectFrom('owa_domstream'); - $db->selectColumn("domstream_guid, max(timestamp) as timestamp, page_url, duration"); - //$db->selectColumn('id'); - $db->selectColumn('document_id'); - $db->groupby('domstream_guid'); - //$db->selectColumn('events'); - $db->where('yyyymmdd', array('start' => $start_date, 'end' => $end_date), 'BETWEEN'); - if ($document_id) { - $db->where('document_id', $document_id); - } - - if ($siteId) { - $db->where('site_id', $siteId); - } - - $db->orderBy('timestamp', 'DESC'); - - // pass limit to rs object if one exists - $rs->setLimit($resultsPerPage); - - // pass page to rs object if one exists - $rs->setPage($page); - - $results = $rs->generate($db); - - $rs->setLabels(array('id' => 'Domstream ID', 'page_url' => 'Page Url', 'duration' => 'Duration', 'timestamp' => 'Timestamp')); - - if ($format) { - owa_lib::setContentTypeHeader($format); - return $rs->formatResults($format); - } else { - return $rs; - } - } - - // api method callback gets an individual domstream - function getDomstream( $domstream_guid ) { - - if ( ! $domstream_guid ) { - return; - } - // Fetch document object - $d = owa_coreAPI::entityFactory('base.domstream'); - //$d->load($this->getParam('domstream_id')); - //$json = new Services_JSON(); - //$d->set('events', $json->decode($d->get('events'))); - - $db = owa_coreAPI::dbSingleton(); - $db->select('*'); - $db->from( $d->getTableName() ); - $db->where( 'domstream_guid', $domstream_guid ); - $db->orderBy('timestamp', 'ASC'); - $ret = $db->getAllRows(); - //print_r($ret); - $combined = ''; - - if ( $ret ) { - // if rows then combine the events - foreach ($ret as $row) { - $combined = $this->mergeStreamEvents( htmlspecialchars_decode( $row['events'] ), $combined ); - } - - $row['events'] = json_decode( $combined ); - } else { - // no rows found for some reason.. - $error = 'No domstream rows found for domstream_guid: ' . $domstream_guid; - owa_coreAPI::debug( $error ); - $row = array('errors' => $error); - } - - $t = new owa_template; - $t->set_template('json.php'); - //$json = new Services_JSON(); - // set - - // if not found look on the request scope. - $callback = owa_coreAPI::getRequestParam('jsonpCallback'); - if ( ! $callback ) { - - $t->set('json', json_encode( $row ) ); - } else { - $body = sprintf("%s(%s);", $callback, json_encode( $row ) ); - $t->set('json', $body); - } - return $t->fetch(); - } - - function mergeStreamEvents($new, $old = '') { - - if ( $old) { - $old = json_decode($old); - } else { - $old = array(); - } - owa_coreAPI::debug('old: '.print_r($old, true)); - $new = json_decode($new); - owa_coreAPI::debug('new: '.print_r($new, true)); - //$combined = array_merge($old, $new); - //array_splice($old, count($old), 0, $new); - - foreach ($new as $v) { - $old[] = $v; - } - $combined = $old; - owa_coreAPI::debug('combined: '.print_r($combined, true)); - owa_coreAPI::debug('combined count: '.count($combined)); - $combined = json_encode($combined); - return $combined; - + + function __construct() { + + $this->name = 'domstream'; + $this->display_name = 'Domstream'; + $this->group = 'logging'; + $this->author = 'Peter Adams'; + $this->version = '1.0'; + $this->description = 'Logs the users mouse and other DOM movements.'; + $this->config_required = false; + $this->required_schema_version = 1; + + // register named queues + + return parent::__construct(); + } + + function registerFilters() { + + // adds tracking cmd to js tracker. + if ( owa_coreAPI::getSetting( 'domstream', 'is_active' ) ) { + + $this->registerFilter('tracker_tag_cmds', $this, 'addToTracker', 99); + } + } + + /** + * Adds domstream logging to the JS tracker tag. + * @return array + */ + function addToTracker( $cmds ) { + + $cmds[] = "owa_cmds.push(['trackDomStream']);"; + + return $cmds; + } + + /** + * Registers Event Handlers with queue queue + * + */ + function _registerEventHandlers() { + + $this->registerEventHandler('dom.stream', 'domstreamHandlers'); + } + + /** + * Registers Reports in Main Navigation + * + */ + function registerNavigation() { + + $this->addNavigationLinkInSubGroup( 'Content', 'base.reportDomstreams', 'Domstreams', 5); + } + + /** + * Register API methods + * + */ + function registerApiMethods() { + + $this->registerApiMethod('getDomstreams', + array( $this, 'getDomstreams' ), + array( + 'startDate', + 'endDate', + 'document_id', + 'siteId', + 'resultsPerPage', + 'page', + 'format' ), + '', + 'view_reports' + ); + + $this->registerApiMethod('getDomstream', + array($this, 'getDomstream'), + array('domstream_guid'), + '', + 'view_reports' + ); + } + + // api method callback + function getDomstreams($start_date, $end_date, $document_id = '', $siteId = '', $resultsPerPage = 20, $page = 1, $format = '') { + + $rs = owa_coreAPI::supportClassFactory('base', 'paginatedResultSet'); + $db = owa_coreAPI::dbSingleton(); + $db->selectFrom('owa_domstream'); + $db->selectColumn("domstream_guid, max(timestamp) as timestamp, page_url, duration"); + //$db->selectColumn('id'); + $db->selectColumn('document_id'); + $db->groupby('domstream_guid'); + //$db->selectColumn('events'); + $db->where('yyyymmdd', array('start' => $start_date, 'end' => $end_date), 'BETWEEN'); + if ($document_id) { + $db->where('document_id', $document_id); + } + + if ($siteId) { + $db->where('site_id', $siteId); + } + + $db->orderBy('timestamp', 'DESC'); + + // pass limit to rs object if one exists + $rs->setLimit($resultsPerPage); + + // pass page to rs object if one exists + $rs->setPage($page); + + $results = $rs->generate($db); + + $rs->setLabels(array('id' => 'Domstream ID', 'page_url' => 'Page Url', 'duration' => 'Duration', 'timestamp' => 'Timestamp')); + + if ($format) { + owa_lib::setContentTypeHeader($format); + return $rs->formatResults($format); + } else { + return $rs; + } + } + + // api method callback gets an individual domstream + function getDomstream( $domstream_guid ) { + + if ( ! $domstream_guid ) { + return; + } + // Fetch document object + $d = owa_coreAPI::entityFactory('base.domstream'); + //$d->load($this->getParam('domstream_id')); + //$json = new Services_JSON(); + //$d->set('events', $json->decode($d->get('events'))); + + $db = owa_coreAPI::dbSingleton(); + $db->select('*'); + $db->from( $d->getTableName() ); + $db->where( 'domstream_guid', $domstream_guid ); + $db->orderBy('timestamp', 'ASC'); + $ret = $db->getAllRows(); + //print_r($ret); + $combined = ''; + + if ( $ret ) { + // if rows then combine the events + foreach ($ret as $row) { + $combined = $this->mergeStreamEvents( htmlspecialchars_decode( $row['events'] ), $combined ); + } + + $row['events'] = json_decode( $combined ); + } else { + // no rows found for some reason�.. + $error = 'No domstream rows found for domstream_guid: ' . $domstream_guid; + owa_coreAPI::debug( $error ); + $row = array('errors' => $error); + } + + $t = new owa_template; + $t->set_template('json.php'); + //$json = new Services_JSON(); + // set + + // if not found look on the request scope. + $callback = owa_coreAPI::getRequestParam('jsonpCallback'); + if ( ! $callback ) { + + $t->set('json', json_encode( $row ) ); + } else { + $body = sprintf("%s(%s);", $callback, json_encode( $row ) ); + $t->set('json', $body); + } + return $t->fetch(); + } + + function mergeStreamEvents($new, $old = '') { + + if ( $old) { + $old = json_decode($old); + } else { + $old = array(); + } + owa_coreAPI::debug('old: '.print_r($old, true)); + $new = json_decode($new); + owa_coreAPI::debug('new: '.print_r($new, true)); + //$combined = array_merge($old, $new); + //array_splice($old, count($old), 0, $new); + + foreach ($new as $v) { + $old[] = $v; + } + $combined = $old; + owa_coreAPI::debug('combined: '.print_r($combined, true)); + owa_coreAPI::debug('combined count: '.count($combined)); + $combined = json_encode($combined); + return $combined; + } - - + + } \ No newline at end of file diff --git a/modules/hello/exampleSettings.php b/modules/hello/exampleSettings.php index b0bd33701..4c41a967e 100644 --- a/modules/hello/exampleSettings.php +++ b/modules/hello/exampleSettings.php @@ -28,26 +28,26 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.3.0 + * @version $Revision$ + * @since owa 1.3.0 */ class owa_exampleSettingsController extends owa_adminController { - - function __construct($params) { - - parent::__construct($params); - $this->type = 'options'; - $this->setRequiredCapability('edit_settings'); - } - - function action() { - - // add data to container - $this->setView('base.options'); - $this->setSubview('base.exampleSettings'); - } - + + function __construct($params) { + + parent::__construct($params); + $this->type = 'options'; + $this->setRequiredCapability('edit_settings'); + } + + function action() { + + // add data to container + $this->setView('base.options'); + $this->setSubview('base.exampleSettings'); + } + } /** @@ -58,27 +58,27 @@ function action() { * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_exampleSettingsView extends owa_view { - - function __construct($params) { - //set page type - $this->_setPageType('Administration Page'); - return parent::__construct($params); - } - - function render($data) { - - // load template - $this->body->setTemplateFile('hello', 'example_settings.php'); - // assign headline - $this->body->set('headline', 'Example Settings Page'); - } - - + + function __construct($params) { + //set page type + $this->_setPageType('Administration Page'); + return parent::__construct($params); + } + + function render($data) { + + // load template + $this->body->setTemplateFile('hello', 'example_settings.php'); + // assign headline + $this->body->set('headline', 'Example Settings Page'); + } + + } diff --git a/modules/hello/module.php b/modules/hello/module.php index b29db1197..02d9d2286 100644 --- a/modules/hello/module.php +++ b/modules/hello/module.php @@ -1,96 +1,96 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_helloModule extends owa_module { - - - function __construct() { - - $this->name = 'hello'; - $this->display_name = 'Hello World'; - $this->group = 'hello'; - $this->author = 'Peter Adams'; - $this->version = '1.0'; - $this->description = 'Hello world sample module.'; - $this->config_required = false; - $this->required_schema_version = 1; - - return parent::__construct(); - } - - /** - * Registers Admin panels with the core API - * - */ - function registerAdminPanels() { - - $this->addAdminPanel(array( 'do' => 'hello.exampleSettings', - 'priviledge' => 'admin', - 'anchortext' => 'Hello World!', - 'group' => 'Test', - 'order' => 1)); - - - return; - - } - - public function registerNavigation() { - $this->addNavigationSubGroup('Hello World', 'hello.reportDashboard', 'Hello Dashboard'); - $this->addNavigationLinkInSubGroup('Hello World','hello.reportSearchterms','also to the dashboard',1); - - } - - /** - * Registers Event Handlers with queue queue - * - */ - function _registerEventHandlers() { - - - // Clicks - //$this->_addHandler('base.click', 'clickHandlers'); - - return; - - } - - function _registerEntities() { - - //$this->entities[] = 'myentity'; - } - - -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_helloModule extends owa_module { + + + function __construct() { + + $this->name = 'hello'; + $this->display_name = 'Hello World'; + $this->group = 'hello'; + $this->author = 'Peter Adams'; + $this->version = '1.0'; + $this->description = 'Hello world sample module.'; + $this->config_required = false; + $this->required_schema_version = 1; + + return parent::__construct(); + } + + /** + * Registers Admin panels with the core API + * + */ + function registerAdminPanels() { + + $this->addAdminPanel(array( 'do' => 'hello.exampleSettings', + 'priviledge' => 'admin', + 'anchortext' => 'Hello World!', + 'group' => 'Test', + 'order' => 1)); + + + return; + + } + + public function registerNavigation() { + $this->addNavigationSubGroup('Hello World', 'hello.reportDashboard', 'Hello Dashboard'); + $this->addNavigationLinkInSubGroup('Hello World','hello.reportSearchterms','also to the dashboard',1); + + } + + /** + * Registers Event Handlers with queue queue + * + */ + function _registerEventHandlers() { + + + // Clicks + //$this->_addHandler('base.click', 'clickHandlers'); + + return; + + } + + function _registerEntities() { + + //$this->entities[] = 'myentity'; + } + + +} + + ?> \ No newline at end of file diff --git a/modules/maxmind_geoip/classes/maxmind.php b/modules/maxmind_geoip/classes/maxmind.php index 26e55a8bc..dd724ae7f 100644 --- a/modules/maxmind_geoip/classes/maxmind.php +++ b/modules/maxmind_geoip/classes/maxmind.php @@ -19,26 +19,26 @@ require_once( OWA_BASE_DIR.'/owa_location.php' ); if(!class_exists('\MaxMind\Db\Reader')){ - require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader.php' ); + require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader.php' ); } if (!class_exists('MaxMind\Db\Reader\Decoder')) { - require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/Decoder.php' ); + require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/Decoder.php' ); } if (!class_exists('MaxMind\Db\Reader\InvalidDatabaseException')) { - require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/InvalidDatabaseException.php' ); + require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/InvalidDatabaseException.php' ); } if (!class_exists('MaxMind\Db\Reader\Metadata')) { - require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/Metadata.php' ); + require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/Metadata.php' ); } if (!class_exists('MaxMind\Db\Reader\Util')) { - require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/Util.php' ); + require_once( OWA_MODULES_DIR . 'maxmind_geoip/includes/MaxMind-DB-Reader-php-1.0.3/src/MaxMind/Db/Reader/Util.php' ); } use MaxMind\Db\Reader; if ( ! defined( 'OWA_MAXMIND_DATA_DIR' ) ) { - define('OWA_MAXMIND_DATA_DIR', OWA_DATA_DIR.'maxmind/'); + define('OWA_MAXMIND_DATA_DIR', OWA_DATA_DIR.'maxmind/'); } /** @@ -51,160 +51,160 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_maxmind extends owa_location { - - /** - * URL template for REST based web service - * - * @var unknown_type - */ - var $ws_url = ''; - var $db_file_dir; - var $db_file_name = 'GeoLite2-City.mmdb'; - var $db_file_path; - var $db_file_present = false; - - /** - * Constructor - * - * @return owa_hostip - */ - function __construct() { - - return parent::__construct(); - } - - function isDbReady() { - - $this->db_file_path = OWA_MAXMIND_DATA_DIR.$this->db_file_name; - - if ( file_exists( $this->db_file_path ) ) { - - $this->db_file_present = true; - } else { - - owa_coreAPI::notice('Maxmind DB file could is not present at: ' . OWA_MAXMIND_DATA_DIR); - } - - return $this->db_file_present; - } - - /** - * Fetches the location from the Maxmind local db - * - * @param string $ip - */ - function getLocation( $location_map ) { - - if ( ! $this->isDbReady() ) { - - return $location_map; - } - - if ( ! array_key_exists( 'ip_address', $location_map ) ) { - return $location_map; - } - - $reader = new Reader( $this->db_file_path ); - - $record = $reader->get( trim( $location_map['ip_address'] ) ); - - $reader->close(); - - if ( $record ) { - - $location_map = $this->mapCityRecord( $record, $location_map ); - } - - return $location_map; - } - - - function getLocationFromWebService($location_map) { - - $license_key = owa_coreAPI::getSetting('maxmind_geoip', 'ws_license_key'); - $user_name = owa_coreAPI::getSetting('maxmind_geoip', 'ws_user_name'); - - if ( ! array_key_exists( 'ip_address', $location_map ) ) { - return $location_map; - } - - - //use GeoIp2\WebService\Client; - - $client = new Client( $user_name, $license_key ); - - $record = $client->city( trim( $location_map['ip_address'] ) ); - - - if ( $record ) { - - $location_map = $this->mapCityRecord( $record, $location_map ); - } - - return $location_map; - } - - private function mapCityRecord( $record, $location_map = array(), $lang = 'en' ) { - - if ( $record && is_array( $record ) ) { - - if ( isset( $record['city']['names'][ $lang ] ) ) { - - $location_map['city'] = utf8_encode( strtolower( trim( $record['city']['names'][ $lang ] ) ) ); - } - - if ( isset( $record['continent']['code'] ) ) { - - $location_map['continent'] = utf8_encode( strtolower( trim( $record['continent']['code'] ) ) ); - } - - if ( isset( $record['continent']['names'][ $lang ] ) ) { - - $location_map['continent_code'] = utf8_encode( strtolower( trim( $record['continent']['names'][ $lang ] ) ) ); - } - - if ( isset( $record['subdivisions'][0]['names'][ $lang ] ) ) { - - $location_map['state'] = utf8_encode( strtolower( trim( $record['subdivisions'][0]['names'][ $lang ] ) ) ); - } - - if ( isset( $record['subdivisions'][0]['iso_code'] ) ) { - - $location_map['state_code'] = utf8_encode( strtolower( trim( $record['subdivisions'][0]['iso_code'] ) ) ); - } - - if ( isset( $record['country']['names'][ $lang ] ) ) { - - $location_map['country'] = utf8_encode( strtolower( trim( $record['country']['names'][ $lang ] ) ) ); - } - - if ( isset( $record['country']['iso_code'] ) ) { - - $location_map['country_code'] = strtoupper( trim( $record['country']['iso_code'] ) ); - } - - if ( isset( $record['location']['latitude'] ) ) { - - $location_map['latitude'] = trim( $record['location']['latitude'] ); - } - - if ( isset( $record['location']['longitude'] ) ) { - - $location_map['longitude'] = trim( $record['location']['longitude'] ); - } - - if ( isset( $record['postal']['code'] ) ) { - - $location_map['postal_code'] = trim( $record['postal']['code'] ); - } - } - - return $location_map; - } + + /** + * URL template for REST based web service + * + * @var unknown_type + */ + var $ws_url = ''; + var $db_file_dir; + var $db_file_name = 'GeoLite2-City.mmdb'; + var $db_file_path; + var $db_file_present = false; + + /** + * Constructor + * + * @return owa_hostip + */ + function __construct() { + + return parent::__construct(); + } + + function isDbReady() { + + $this->db_file_path = OWA_MAXMIND_DATA_DIR.$this->db_file_name; + + if ( file_exists( $this->db_file_path ) ) { + + $this->db_file_present = true; + } else { + + owa_coreAPI::notice('Maxmind DB file could is not present at: ' . OWA_MAXMIND_DATA_DIR); + } + + return $this->db_file_present; + } + + /** + * Fetches the location from the Maxmind local db + * + * @param string $ip + */ + function getLocation( $location_map ) { + + if ( ! $this->isDbReady() ) { + + return $location_map; + } + + if ( ! array_key_exists( 'ip_address', $location_map ) ) { + return $location_map; + } + + $reader = new Reader( $this->db_file_path ); + + $record = $reader->get( trim( $location_map['ip_address'] ) ); + + $reader->close(); + + if ( $record ) { + + $location_map = $this->mapCityRecord( $record, $location_map ); + } + + return $location_map; + } + + + function getLocationFromWebService($location_map) { + + $license_key = owa_coreAPI::getSetting('maxmind_geoip', 'ws_license_key'); + $user_name = owa_coreAPI::getSetting('maxmind_geoip', 'ws_user_name'); + + if ( ! array_key_exists( 'ip_address', $location_map ) ) { + return $location_map; + } + + + //use GeoIp2\WebService\Client; + + $client = new Client( $user_name, $license_key ); + + $record = $client->city( trim( $location_map['ip_address'] ) ); + + + if ( $record ) { + + $location_map = $this->mapCityRecord( $record, $location_map ); + } + + return $location_map; + } + + private function mapCityRecord( $record, $location_map = array(), $lang = 'en' ) { + + if ( $record && is_array( $record ) ) { + + if ( isset( $record['city']['names'][ $lang ] ) ) { + + $location_map['city'] = utf8_encode( strtolower( trim( $record['city']['names'][ $lang ] ) ) ); + } + + if ( isset( $record['continent']['code'] ) ) { + + $location_map['continent'] = utf8_encode( strtolower( trim( $record['continent']['code'] ) ) ); + } + + if ( isset( $record['continent']['names'][ $lang ] ) ) { + + $location_map['continent_code'] = utf8_encode( strtolower( trim( $record['continent']['names'][ $lang ] ) ) ); + } + + if ( isset( $record['subdivisions'][0]['names'][ $lang ] ) ) { + + $location_map['state'] = utf8_encode( strtolower( trim( $record['subdivisions'][0]['names'][ $lang ] ) ) ); + } + + if ( isset( $record['subdivisions'][0]['iso_code'] ) ) { + + $location_map['state_code'] = utf8_encode( strtolower( trim( $record['subdivisions'][0]['iso_code'] ) ) ); + } + + if ( isset( $record['country']['names'][ $lang ] ) ) { + + $location_map['country'] = utf8_encode( strtolower( trim( $record['country']['names'][ $lang ] ) ) ); + } + + if ( isset( $record['country']['iso_code'] ) ) { + + $location_map['country_code'] = strtoupper( trim( $record['country']['iso_code'] ) ); + } + + if ( isset( $record['location']['latitude'] ) ) { + + $location_map['latitude'] = trim( $record['location']['latitude'] ); + } + + if ( isset( $record['location']['longitude'] ) ) { + + $location_map['longitude'] = trim( $record['location']['longitude'] ); + } + + if ( isset( $record['postal']['code'] ) ) { + + $location_map['postal_code'] = trim( $record['postal']['code'] ); + } + } + + return $location_map; + } } diff --git a/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP.php b/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP.php index d621d91aa..a0d2a012c 100644 --- a/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP.php +++ b/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP.php @@ -1,904 +1,904 @@ - (original Maxmind version) | - * | Hans Lellelid | - * +----------------------------------------------------------------------+ - * - * @category Net - * @package Net_GeoIP - * @author Jim Winstead (original Maxmind PHP API) - * @author Hans Lellelid - * @license LGPL http://www.gnu.org/licenses/lgpl.txt - * @link http://pear.php.net/package/Net_GeoIp - * $Id: GeoIP.php 296763 2010-03-25 00:53:44Z clockwerx $ - */ - -require_once 'PEAR/Exception.php'; - -/** - * GeoIP class provides an API for performing geo-location lookups based on IP - * address. - * - * To use this class you must have a [binary version] GeoIP database. There is - * a free GeoIP country database which can be obtained from Maxmind: - * {@link http://www.maxmind.com/app/geoip_country} - * - * - * SIMPLE USE - * - * - * Create an instance: - * - * - * $geoip = Net_GeoIP::getInstance('/path/to/geoipdb.dat', Net_GeoIP::SHARED_MEMORY); - * - * - * Depending on which database you are using (free, or one of paid versions) - * you must use appropriate lookup method: - * - * - * // for free country db: - * $country_name = $geoip->lookupCountryName($_SERVER['REMOTE_ADDR']); - * $country_code = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']); - * - * // for [non-free] region db: - * list($ctry_code, $region) = $geoip->lookupRegion($_SERVER['REMOTE_ADDR']); - * - * // for [non-free] city db: - * $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']); - * print "city: " . $location->city . ", " . $location->region; - * print "lat: " . $location->latitude . ", long: " . $location->longitude; - * - * // for organization or ISP db: - * $org_or_isp_name = $geoip->lookupOrg($_SERVER['REMOTE_ADDR']); - * - * - * - * MULTIPLE INSTANCES - * - * - * You can have several instances of this class, one for each database file - * you are using. You should use the static getInstance() singleton method - * to save on overhead of setting up database segments. Note that only one - * instance is stored per filename, and any flags will be ignored if an - * instance already exists for the specifiedfilename. - * - * Special note on using SHARED_MEMORY flag - * - * If you are using SHARED_MEMORY (shmop) you can only use SHARED_MEMORY for - * one (1) instance (i.e. for one database). Any subsequent attempts to - * instantiate using SHARED_MEMORY will read the same shared memory block - * already initialized, and therefore will cause problems since the expected - * database format won't match the database in the shared memory block. - * - * Note that there is no easy way to flag "nice errors" to prevent attempts - * to create new instances using SHARED_MEMORY flag and it is also not posible - * (in a safe way) to allow new instances to overwrite the shared memory block. - * - * In short, is you are using multiple databses, use the SHARED_MEMORY flag - * with care. - * - * - * LOOKUPS ON HOSTNAMES - * - * - * Note that this PHP API does NOT support lookups on hostnames. This is so - * that the public API can be kept simple and so that the lookup functions - * don't need to try name lookups if IP lookup fails (which would be the only - * way to keep the API simple and support name-based lookups). - * - * If you do not know the IP address, you can convert an name to IP very - * simply using PHP native functions or other libraries: - * - * - * $geoip->lookupCountryName(gethostbyname('www.sunset.se')); - * - * - * Or, if you don't know whether an address is a name or ip address, use - * application-level logic: - * - * - * if (ip2long($ip_or_name) === false) { - * $ip = gethostbyname($ip_or_name); - * } else { - * $ip = $ip_or_name; - * } - * $ctry = $geoip->lookupCountryName($ip); - * - * - * @category Net - * @package Net_GeoIP - * @author Jim Winstead (original Maxmind PHP API) - * @author Hans Lellelid - * @license LGPL http://www.gnu.org/licenses/lgpl.txt - * @link http://pear.php.net/package/Net_GeoIp - */ -class Net_GeoIP -{ - /** - * Exception error code used for invalid IP address. - */ - const ERR_INVALID_IP = 218624992; // crc32('Net_GeoIP::ERR_INVALID_IP') - - /** - * Exception error code when there is a DB-format-related error. - */ - const ERR_DB_FORMAT = 866184008; // crc32('Net_GeoIP::ERR_DB_FORMAT') - - public static $COUNTRY_CODES = array( - "", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", - "AR", "AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", - "BI", "BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", - "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", - "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", - "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB", - "GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", - "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", - "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", - "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", - "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", - "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", - "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", - "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", - "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", - "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", - "TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW", - "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", - "VU", "WF", "WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", - "AX", "GG", "IM", "JE", "BL", "MF" - ); - - public static $COUNTRY_CODES3 = array( - "","AP","EU","AND","ARE","AFG","ATG","AIA","ALB","ARM","ANT","AGO","AQ","ARG", - "ASM","AUT","AUS","ABW","AZE","BIH","BRB","BGD","BEL","BFA","BGR","BHR","BDI", - "BEN","BMU","BRN","BOL","BRA","BHS","BTN","BV","BWA","BLR","BLZ","CAN","CC", - "COD","CAF","COG","CHE","CIV","COK","CHL","CMR","CHN","COL","CRI","CUB","CPV", - "CX","CYP","CZE","DEU","DJI","DNK","DMA","DOM","DZA","ECU","EST","EGY","ESH", - "ERI","ESP","ETH","FIN","FJI","FLK","FSM","FRO","FRA","FX","GAB","GBR","GRD", - "GEO","GUF","GHA","GIB","GRL","GMB","GIN","GLP","GNQ","GRC","GS","GTM","GUM", - "GNB","GUY","HKG","HM","HND","HRV","HTI","HUN","IDN","IRL","ISR","IND","IO", - "IRQ","IRN","ISL","ITA","JAM","JOR","JPN","KEN","KGZ","KHM","KIR","COM","KNA", - "PRK","KOR","KWT","CYM","KAZ","LAO","LBN","LCA","LIE","LKA","LBR","LSO","LTU", - "LUX","LVA","LBY","MAR","MCO","MDA","MDG","MHL","MKD","MLI","MMR","MNG","MAC", - "MNP","MTQ","MRT","MSR","MLT","MUS","MDV","MWI","MEX","MYS","MOZ","NAM","NCL", - "NER","NFK","NGA","NIC","NLD","NOR","NPL","NRU","NIU","NZL","OMN","PAN","PER", - "PYF","PNG","PHL","PAK","POL","SPM","PCN","PRI","PSE","PRT","PLW","PRY","QAT", - "REU","ROU","RUS","RWA","SAU","SLB","SYC","SDN","SWE","SGP","SHN","SVN","SJM", - "SVK","SLE","SMR","SEN","SOM","SUR","STP","SLV","SYR","SWZ","TCA","TCD","TF", - "TGO","THA","TJK","TKL","TLS","TKM","TUN","TON","TUR","TTO","TUV","TWN","TZA", - "UKR","UGA","UM","USA","URY","UZB","VAT","VCT","VEN","VGB","VIR","VNM","VUT", - "WLF","WSM","YEM","YT","SRB","ZAF","ZMB","MNE","ZWE","A1","A2","O1", - "ALA","GGY","IMN","JEY","BLM","MAF" - ); - - public static $COUNTRY_NAMES = array( - "", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", - "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", - "Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa", - "Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", - "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", - "Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", - "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", - "Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", - "Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook Islands", - "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde", - "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", - "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", - "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", - "Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe Islands", - "France", "France, Metropolitan", "Gabon", "United Kingdom", - "Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", - "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands", - "Guatemala", "Guam", "Guinea-Bissau", - "Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", - "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", - "British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", - "Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", - "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic People's Republic of", - "Korea, Republic of", "Kuwait", "Cayman Islands", - "Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", - "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", - "Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic of", - "Madagascar", "Marshall Islands", "Macedonia", - "Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands", - "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", - "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", - "Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", - "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia", - "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon", - "Pitcairn Islands", "Puerto Rico", "Palestinian Territory", - "Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", - "Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", - "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", - "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", - "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab Republic", - "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern Territories", - "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", - "Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu", - "Taiwan", "Tanzania, United Republic of", "Ukraine", - "Uganda", "United States Minor Outlying Islands", "United States", "Uruguay", - "Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the Grenadines", - "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", - "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", - "Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe", - "Anonymous Proxy","Satellite Provider","Other", - "Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy","Saint Martin" - ); - - // storage / caching flags - const STANDARD = 0; - const MEMORY_CACHE = 1; - const SHARED_MEMORY = 2; - - // Database structure constants - const COUNTRY_BEGIN = 16776960; - const STATE_BEGIN_REV0 = 16700000; - const STATE_BEGIN_REV1 = 16000000; - - const STRUCTURE_INFO_MAX_SIZE = 20; - const DATABASE_INFO_MAX_SIZE = 100; - const COUNTRY_EDITION = 106; - const REGION_EDITION_REV0 = 112; - const REGION_EDITION_REV1 = 3; - const CITY_EDITION_REV0 = 111; - const CITY_EDITION_REV1 = 2; - const ORG_EDITION = 110; - const SEGMENT_RECORD_LENGTH = 3; - const STANDARD_RECORD_LENGTH = 3; - const ORG_RECORD_LENGTH = 4; - const MAX_RECORD_LENGTH = 4; - const MAX_ORG_RECORD_LENGTH = 300; - const FULL_RECORD_LENGTH = 50; - - const US_OFFSET = 1; - const CANADA_OFFSET = 677; - const WORLD_OFFSET = 1353; - const FIPS_RANGE = 360; - - // SHMOP memory address - const SHM_KEY = 0x4f415401; - - /** - * @var int - */ - private $flags = 0; - - /** - * @var resource - */ - private $filehandle; - - /** - * @var string - */ - private $memoryBuffer; - - /** - * @var int - */ - private $databaseType; - - /** - * @var int - */ - private $databaseSegments; - - /** - * @var int - */ - private $recordLength; - - /** - * The memory addr "id" for use with SHMOP. - * @var int - */ - private $shmid; - - /** - * Support for singleton pattern. - * @var array - */ - private static $instances = array(); - - /** - * Construct a Net_GeoIP instance. - * You should use the getInstance() method if you plan to use multiple databases or - * the same database from several different places in your script. - * - * @param string $filename Path to binary geoip database. - * @param int $flags Flags - * - * @see getInstance() - */ - public function __construct($filename = null, $flags = null) - { - if ($filename !== null) { - $this->open($filename, $flags); - } - // store the instance, so that it will be returned by a call to - // getInstance() (with the same db filename). - self::$instances[$filename] = $this; - } - - /** - * Calls the close() function to free any resources. - * @see close() - * - * COMMENTED OUT TO ADDRESS BUG IN PHP 5.0.4, 5.0.5dev. THIS RESOURCE - * SHOULD AUTOMATICALLY BE FREED AT SCRIPT CLOSE, SO A DESTRUCTOR - * IS A GOOD IDEA BUT NOT NECESSARILY A NECESSITY. - public function __destruct() - { - $this->close(); - } - */ - - /** - * Singleton method, use this to get an instance and avoid re-parsing the db. - * - * Unique instances are instantiated based on the filename of the db. The flags - * are ignored -- in that requests to for instance with same filename but different - * flags will return the already-instantiated instance. For example: - * - * // create new instance with memory_cache enabled - * $geoip = Net_GeoIP::getInstance('C:\mydb.dat', Net_GeoIP::MEMORY_CACHE); - * .... - * - * // later in code, request instance with no flags specified. - * $geoip = Net_GeoIP::getInstance('C:\mydb.dat'); - * - * // Normally this means no MEMORY_CACHE but since an instance - * // with memory cache enabled has already been created for 'C:\mydb.dat', the - * // existing instance (with memory cache) will be returned. - * - * - * NOTE: You can only use SHARED_MEMORY flag for one instance! Any subsquent instances - * that attempt to use the SHARED_MEMORY will use the *same* shared memory, which will break - * your script. - * - * @param string $filename Filename - * @param int $flags Flags that control class behavior. - * + Net_GeoIp::SHARED_MEMORY - * Use SHMOP to share a db among multiple PHP instances. - * NOTE: ONLY ONE GEOIP INSTANCE CAN USE SHARED MEMORY!!! - * + Net_GeoIp::MEMORY_CACHE - * Store the full contents of the database in memory for current script. - * This is useful if you access the database several times in a script. - * + Net_GeoIp::STANDARD - * [default] standard no-cache version. - * - * @return Net_GeoIP - */ - public static function getInstance($filename = null, $flags = null) - { - if (!isset(self::$instances[$filename])) { - self::$instances[$filename] = new Net_GeoIP($filename, $flags); - } - return self::$instances[$filename]; - } - - /** - * Opens geoip database at filename and with specified flags. - * - * @param string $filename File to open - * @param int $flags Flags - * - * @return void - * - * @throws PEAR_Exception if unable to open specified file or shared memory. - */ - public function open($filename, $flags = null) - { - if ($flags !== null) { - $this->flags = $flags; - } - if ($this->flags & self::SHARED_MEMORY) { - $this->shmid = @shmop_open(self::SHM_KEY, "a", 0, 0); - if ($this->shmid === false) { - $this->loadSharedMemory($filename); - $this->shmid = @shmop_open(self::SHM_KEY, "a", 0, 0); - if ($this->shmid === false) { // should never be false as loadSharedMemory() will throw Exc if cannot create - throw new PEAR_Exception("Unable to open shared memory at key: " . dechex(self::SHM_KEY)); - } - } - } else { - $this->filehandle = fopen($filename, "rb"); - if (!$this->filehandle) { - throw new PEAR_Exception("Unable to open file: $filename"); - } - if ($this->flags & self::MEMORY_CACHE) { - $s_array = fstat($this->filehandle); - $this->memoryBuffer = fread($this->filehandle, $s_array['size']); - } - } - $this->setupSegments(); - } - - /** - * Loads the database file into shared memory. - * - * @param string $filename Path to database file to read into shared memory. - * - * @return void - * - * @throws PEAR_Exception - if unable to read the db file. - */ - protected function loadSharedMemory($filename) - { - $fp = fopen($filename, "rb"); - if (!$fp) { - throw new PEAR_Exception("Unable to open file: $filename"); - } - $s_array = fstat($fp); - $size = $s_array['size']; - - if ($shmid = @shmop_open(self::SHM_KEY, "w", 0, 0)) { - shmop_delete($shmid); - shmop_close($shmid); - } - - if ($shmid = @shmop_open(self::SHM_KEY, "c", 0644, $size)) { - $offset = 0; - while ($offset < $size) { - $buf = fread($fp, 524288); - shmop_write($shmid, $buf, $offset); - $offset += 524288; - } - shmop_close($shmid); - } - - fclose($fp); - } - - /** - * Parses the database file to determine what kind of database is being used and setup - * segment sizes and start points that will be used by the seek*() methods later. - * - * @return void - */ - protected function setupSegments() - { - - $this->databaseType = self::COUNTRY_EDITION; - $this->recordLength = self::STANDARD_RECORD_LENGTH; - - if ($this->flags & self::SHARED_MEMORY) { - - $offset = shmop_size($this->shmid) - 3; - for ($i = 0; $i < self::STRUCTURE_INFO_MAX_SIZE; $i++) { - $delim = shmop_read($this->shmid, $offset, 3); - $offset += 3; - if ($delim == (chr(255).chr(255).chr(255))) { - $this->databaseType = ord(shmop_read($this->shmid, $offset, 1)); - $offset++; - if ($this->databaseType === self::REGION_EDITION_REV0) { - $this->databaseSegments = self::STATE_BEGIN_REV0; - } elseif ($this->databaseType === self::REGION_EDITION_REV1) { - $this->databaseSegments = self::STATE_BEGIN_REV1; - } elseif (($this->databaseType === self::CITY_EDITION_REV0) - || ($this->databaseType === self::CITY_EDITION_REV1) - || ($this->databaseType === self::ORG_EDITION)) { - $this->databaseSegments = 0; - $buf = shmop_read($this->shmid, $offset, self::SEGMENT_RECORD_LENGTH); - for ($j = 0; $j < self::SEGMENT_RECORD_LENGTH; $j++) { - $this->databaseSegments += (ord($buf[$j]) << ($j * 8)); - } - if ($this->databaseType === self::ORG_EDITION) { - $this->recordLength = self::ORG_RECORD_LENGTH; - } - } - break; - } else { - $offset -= 4; - } - } - if ($this->databaseType == self::COUNTRY_EDITION) { - $this->databaseSegments = self::COUNTRY_BEGIN; - } - - } else { - - $filepos = ftell($this->filehandle); - fseek($this->filehandle, -3, SEEK_END); - for ($i = 0; $i < self::STRUCTURE_INFO_MAX_SIZE; $i++) { - $delim = fread($this->filehandle, 3); - if ($delim == (chr(255).chr(255).chr(255))) { - $this->databaseType = ord(fread($this->filehandle, 1)); - if ($this->databaseType === self::REGION_EDITION_REV0) { - $this->databaseSegments = self::STATE_BEGIN_REV0; - } elseif ($this->databaseType === self::REGION_EDITION_REV1) { - $this->databaseSegments = self::STATE_BEGIN_REV1; - } elseif ($this->databaseType === self::CITY_EDITION_REV0 - || $this->databaseType === self::CITY_EDITION_REV1 - || $this->databaseType === self::ORG_EDITION) { - $this->databaseSegments = 0; - $buf = fread($this->filehandle, self::SEGMENT_RECORD_LENGTH); - for ($j = 0; $j < self::SEGMENT_RECORD_LENGTH; $j++) { - $this->databaseSegments += (ord($buf[$j]) << ($j * 8)); - } - if ($this->databaseType === self::ORG_EDITION) { - $this->recordLength = self::ORG_RECORD_LENGTH; - } - } - break; - } else { - fseek($this->filehandle, -4, SEEK_CUR); - } - } - if ($this->databaseType === self::COUNTRY_EDITION) { - $this->databaseSegments = self::COUNTRY_BEGIN; - } - fseek($this->filehandle, $filepos, SEEK_SET); - - } - } - - /** - * Closes the geoip database. - * - * @return int Status of close command. - */ - public function close() - { - if ($this->flags & self::SHARED_MEMORY) { - return shmop_close($this->shmid); - } else { - // right now even if file was cached in RAM the file was not closed - // so it's safe to expect no error w/ fclose() - return fclose($this->filehandle); - } - } - - /** - * Get the country index. - * - * This method is called by the lookupCountryCode() and lookupCountryName() - * methods. It lookups up the index ('id') for the country which is the key - * for the code and name. - * - * @param string $addr IP address (hostname not allowed) - * - * @throws PEAR_Exception - if IP address is invalid. - * - if database type is incorrect - * - * @return string ID for the country - */ - protected function lookupCountryId($addr) - { - $ipnum = ip2long($addr); - if ($ipnum === false) { - throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); - } - if ($this->databaseType !== self::COUNTRY_EDITION) { - throw new PEAR_Exception("Invalid database type; lookupCountry*() methods expect Country database."); - } - return $this->seekCountry($ipnum) - self::COUNTRY_BEGIN; - } - - /** - * Returns 2-letter country code (e.g. 'CA') for specified IP address. - * Use this method if you have a Country database. - * - * @param string $addr IP address (hostname not allowed). - * - * @return string 2-letter country code - * - * @throws PEAR_Exception (see lookupCountryId()) - * @see lookupCountryId() - */ - public function lookupCountryCode($addr) - { - return self::$COUNTRY_CODES[$this->lookupCountryId($addr)]; - } - - /** - * Returns full country name for specified IP address. - * Use this method if you have a Country database. - * - * @param string $addr IP address (hostname not allowed). - * - * @return string Country name - * @throws PEAR_Exception (see lookupCountryId()) - * @see lookupCountryId() - */ - public function lookupCountryName($addr) - { - return self::$COUNTRY_NAMES[$this->lookupCountryId($addr)]; - } - - /** - * Using the record length and appropriate start points, seek to the country that corresponds - * to the converted IP address integer. - * - * @param int $ipnum Result of ip2long() conversion. - * - * @return int Offset of start of record. - * @throws PEAR_Exception - if fseek() fails on the file or no results after traversing the database (indicating corrupt db). - */ - protected function seekCountry($ipnum) - { - $offset = 0; - for ($depth = 31; $depth >= 0; --$depth) { - if ($this->flags & self::MEMORY_CACHE) { - $buf = substr($this->memoryBuffer, 2 * $this->recordLength * $offset, 2 * $this->recordLength); - } elseif ($this->flags & self::SHARED_MEMORY) { - $buf = shmop_read($this->shmid, 2 * $this->recordLength * $offset, 2 * $this->recordLength); - } else { - if (fseek($this->filehandle, 2 * $this->recordLength * $offset, SEEK_SET) !== 0) { - throw new PEAR_Exception("fseek failed"); - } - $buf = fread($this->filehandle, 2 * $this->recordLength); - } - $x = array(0,0); - for ($i = 0; $i < 2; ++$i) { - for ($j = 0; $j < $this->recordLength; ++$j) { - $x[$i] += ord($buf[$this->recordLength * $i + $j]) << ($j * 8); - } - } - if ($ipnum & (1 << $depth)) { - if ($x[1] >= $this->databaseSegments) { - return $x[1]; - } - $offset = $x[1]; - } else { - if ($x[0] >= $this->databaseSegments) { - return $x[0]; - } - $offset = $x[0]; - } - } - throw new PEAR_Exception("Error traversing database - perhaps it is corrupt?"); - } - - /** - * Lookup the organization (or ISP) for given IP address. - * Use this method if you have an Organization/ISP database. - * - * @param string $addr IP address (hostname not allowed). - * - * @throws PEAR_Exception - if IP address is invalid. - * - if database is of wrong type - * - * @return string The organization - */ - public function lookupOrg($addr) - { - $ipnum = ip2long($addr); - if ($ipnum === false) { - throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); - } - if ($this->databaseType !== self::ORG_EDITION) { - throw new PEAR_Exception("Invalid database type; lookupOrg() method expects Org/ISP database.", self::ERR_DB_FORMAT); - } - return $this->getOrg($ipnum); - } - - /** - * Lookup the region for given IP address. - * Use this method if you have a Region database. - * - * @param string $addr IP address (hostname not allowed). - * - * @return array Array containing country code and region: array($country_code, $region) - * - * @throws PEAR_Exception - if IP address is invalid. - */ - public function lookupRegion($addr) - { - $ipnum = ip2long($addr); - if ($ipnum === false) { - throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); - } - if ($this->databaseType !== self::REGION_EDITION_REV0 && $this->databaseType !== self::REGION_EDITION_REV1) { - throw new PEAR_Exception("Invalid database type; lookupRegion() method expects Region database.", self::ERR_DB_FORMAT); - } - return $this->getRegion($ipnum); - } - - /** - * Lookup the location record for given IP address. - * Use this method if you have a City database. - * - * @param string $addr IP address (hostname not allowed). - * - * @return Net_GeoIP_Location The full location record. - * - * @throws PEAR_Exception - if IP address is invalid. - */ - public function lookupLocation($addr) - { - include_once 'Net/GeoIP/Location.php'; - $ipnum = ip2long($addr); - if ($ipnum === false) { - throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); - } - if ($this->databaseType !== self::CITY_EDITION_REV0 && $this->databaseType !== self::CITY_EDITION_REV1) { - throw new PEAR_Exception("Invalid database type; lookupLocation() method expects City database."); - } - return $this->getRecord($ipnum); - } - - /** - * Seek and return organization (or ISP) name for converted IP addr. - * - * @param int $ipnum Converted IP address. - * - * @return string The organization - */ - protected function getOrg($ipnum) - { - $seek_org = $this->seekCountry($ipnum); - if ($seek_org == $this->databaseSegments) { - return null; - } - $record_pointer = $seek_org + (2 * $this->recordLength - 1) * $this->databaseSegments; - if ($this->flags & self::SHARED_MEMORY) { - $org_buf = shmop_read($this->shmid, $record_pointer, self::MAX_ORG_RECORD_LENGTH); - } else { - fseek($this->filehandle, $record_pointer, SEEK_SET); - $org_buf = fread($this->filehandle, self::MAX_ORG_RECORD_LENGTH); - } - $org_buf = substr($org_buf, 0, strpos($org_buf, 0)); - return $org_buf; - } - - /** - * Seek and return the region info (array containing country code and region name) for converted IP addr. - * - * @param int $ipnum Converted IP address. - * - * @return array Array containing country code and region: array($country_code, $region) - */ - protected function getRegion($ipnum) - { - if ($this->databaseType == self::REGION_EDITION_REV0) { - $seek_region = $this->seekCountry($ipnum) - self::STATE_BEGIN_REV0; - if ($seek_region >= 1000) { - $country_code = "US"; - $region = chr(($seek_region - 1000)/26 + 65) . chr(($seek_region - 1000)%26 + 65); - } else { - $country_code = self::$COUNTRY_CODES[$seek_region]; - $region = ""; - } - return array($country_code, $region); - } elseif ($this->databaseType == self::REGION_EDITION_REV1) { - $seek_region = $this->seekCountry($ipnum) - self::STATE_BEGIN_REV1; - //print $seek_region; - if ($seek_region < self::US_OFFSET) { - $country_code = ""; - $region = ""; - } elseif ($seek_region < self::CANADA_OFFSET) { - $country_code = "US"; - $region = chr(($seek_region - self::US_OFFSET)/26 + 65) . chr(($seek_region - self::US_OFFSET)%26 + 65); - } elseif ($seek_region < self::WORLD_OFFSET) { - $country_code = "CA"; - $region = chr(($seek_region - self::CANADA_OFFSET)/26 + 65) . chr(($seek_region - self::CANADA_OFFSET)%26 + 65); - } else { - $country_code = self::$COUNTRY_CODES[($seek_region - self::WORLD_OFFSET) / self::FIPS_RANGE]; - $region = ""; - } - return array ($country_code,$region); - } - } - - /** - * Seek and populate Net_GeoIP_Location object for converted IP addr. - * Note: this - * - * @param int $ipnum Converted IP address. - * - * @return Net_GeoIP_Location - */ - protected function getRecord($ipnum) - { - $seek_country = $this->seekCountry($ipnum); - if ($seek_country == $this->databaseSegments) { - return null; - } - - $record_pointer = $seek_country + (2 * $this->recordLength - 1) * $this->databaseSegments; - - if ($this->flags & self::SHARED_MEMORY) { - $record_buf = shmop_read($this->shmid, $record_pointer, self::FULL_RECORD_LENGTH); - } else { - fseek($this->filehandle, $record_pointer, SEEK_SET); - $record_buf = fread($this->filehandle, self::FULL_RECORD_LENGTH); - } - - $record = new Net_GeoIP_Location(); - - $record_buf_pos = 0; - $char = ord(substr($record_buf, $record_buf_pos, 1)); - - $record->countryCode = self::$COUNTRY_CODES[$char]; - $record->countryCode3 = self::$COUNTRY_CODES3[$char]; - $record->countryName = self::$COUNTRY_NAMES[$char]; - $record_buf_pos++; - $str_length = 0; - - //get region - $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); - while ($char != 0) { - $str_length++; - $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); - } - if ($str_length > 0) { - $record->region = substr($record_buf, $record_buf_pos, $str_length); - } - $record_buf_pos += $str_length + 1; - $str_length = 0; - - //get city - $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); - while ($char != 0) { - $str_length++; - $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); - } - if ($str_length > 0) { - $record->city = substr($record_buf, $record_buf_pos, $str_length); - } - $record_buf_pos += $str_length + 1; - $str_length = 0; - - //get postal code - $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); - while ($char != 0) { - $str_length++; - $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); - } - if ($str_length > 0) { - $record->postalCode = substr($record_buf, $record_buf_pos, $str_length); - } - $record_buf_pos += $str_length + 1; - $str_length = 0; - $latitude = 0; - $longitude = 0; - for ($j = 0;$j < 3; ++$j) { - $char = ord(substr($record_buf, $record_buf_pos++, 1)); - $latitude += ($char << ($j * 8)); - } - $record->latitude = ($latitude/10000) - 180; - - for ($j = 0;$j < 3; ++$j) { - $char = ord(substr($record_buf, $record_buf_pos++, 1)); - $longitude += ($char << ($j * 8)); - } - $record->longitude = ($longitude/10000) - 180; - - if ($this->databaseType === self::CITY_EDITION_REV1) { - $dmaarea_combo = 0; - if ($record->countryCode == "US") { - for ($j = 0;$j < 3;++$j) { - $char = ord(substr($record_buf, $record_buf_pos++, 1)); - $dmaarea_combo += ($char << ($j * 8)); - } - $record->dmaCode = floor($dmaarea_combo/1000); - $record->areaCode = $dmaarea_combo%1000; - } - } - - return $record; - } - -} - + (original Maxmind version) | + * | Hans Lellelid | + * +----------------------------------------------------------------------+ + * + * @category Net + * @package Net_GeoIP + * @author Jim Winstead (original Maxmind PHP API) + * @author Hans Lellelid + * @license LGPL http://www.gnu.org/licenses/lgpl.txt + * @link http://pear.php.net/package/Net_GeoIp + * $Id: GeoIP.php 296763 2010-03-25 00:53:44Z clockwerx $ + */ + +require_once 'PEAR/Exception.php'; + +/** + * GeoIP class provides an API for performing geo-location lookups based on IP + * address. + * + * To use this class you must have a [binary version] GeoIP database. There is + * a free GeoIP country database which can be obtained from Maxmind: + * {@link http://www.maxmind.com/app/geoip_country} + * + * + * SIMPLE USE + * + * + * Create an instance: + * + * + * $geoip = Net_GeoIP::getInstance('/path/to/geoipdb.dat', Net_GeoIP::SHARED_MEMORY); + * + * + * Depending on which database you are using (free, or one of paid versions) + * you must use appropriate lookup method: + * + * + * // for free country db: + * $country_name = $geoip->lookupCountryName($_SERVER['REMOTE_ADDR']); + * $country_code = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']); + * + * // for [non-free] region db: + * list($ctry_code, $region) = $geoip->lookupRegion($_SERVER['REMOTE_ADDR']); + * + * // for [non-free] city db: + * $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']); + * print "city: " . $location->city . ", " . $location->region; + * print "lat: " . $location->latitude . ", long: " . $location->longitude; + * + * // for organization or ISP db: + * $org_or_isp_name = $geoip->lookupOrg($_SERVER['REMOTE_ADDR']); + * + * + * + * MULTIPLE INSTANCES + * + * + * You can have several instances of this class, one for each database file + * you are using. You should use the static getInstance() singleton method + * to save on overhead of setting up database segments. Note that only one + * instance is stored per filename, and any flags will be ignored if an + * instance already exists for the specifiedfilename. + * + * Special note on using SHARED_MEMORY flag + * + * If you are using SHARED_MEMORY (shmop) you can only use SHARED_MEMORY for + * one (1) instance (i.e. for one database). Any subsequent attempts to + * instantiate using SHARED_MEMORY will read the same shared memory block + * already initialized, and therefore will cause problems since the expected + * database format won't match the database in the shared memory block. + * + * Note that there is no easy way to flag "nice errors" to prevent attempts + * to create new instances using SHARED_MEMORY flag and it is also not posible + * (in a safe way) to allow new instances to overwrite the shared memory block. + * + * In short, is you are using multiple databses, use the SHARED_MEMORY flag + * with care. + * + * + * LOOKUPS ON HOSTNAMES + * + * + * Note that this PHP API does NOT support lookups on hostnames. This is so + * that the public API can be kept simple and so that the lookup functions + * don't need to try name lookups if IP lookup fails (which would be the only + * way to keep the API simple and support name-based lookups). + * + * If you do not know the IP address, you can convert an name to IP very + * simply using PHP native functions or other libraries: + * + * + * $geoip->lookupCountryName(gethostbyname('www.sunset.se')); + * + * + * Or, if you don't know whether an address is a name or ip address, use + * application-level logic: + * + * + * if (ip2long($ip_or_name) === false) { + * $ip = gethostbyname($ip_or_name); + * } else { + * $ip = $ip_or_name; + * } + * $ctry = $geoip->lookupCountryName($ip); + * + * + * @category Net + * @package Net_GeoIP + * @author Jim Winstead (original Maxmind PHP API) + * @author Hans Lellelid + * @license LGPL http://www.gnu.org/licenses/lgpl.txt + * @link http://pear.php.net/package/Net_GeoIp + */ +class Net_GeoIP +{ + /** + * Exception error code used for invalid IP address. + */ + const ERR_INVALID_IP = 218624992; // crc32('Net_GeoIP::ERR_INVALID_IP') + + /** + * Exception error code when there is a DB-format-related error. + */ + const ERR_DB_FORMAT = 866184008; // crc32('Net_GeoIP::ERR_DB_FORMAT') + + public static $COUNTRY_CODES = array( + "", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", + "AR", "AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", + "BI", "BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", + "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", + "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", + "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB", + "GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", + "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", + "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", + "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", + "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", + "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", + "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", + "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", + "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", + "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", + "TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW", + "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", + "VU", "WF", "WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", + "AX", "GG", "IM", "JE", "BL", "MF" + ); + + public static $COUNTRY_CODES3 = array( + "","AP","EU","AND","ARE","AFG","ATG","AIA","ALB","ARM","ANT","AGO","AQ","ARG", + "ASM","AUT","AUS","ABW","AZE","BIH","BRB","BGD","BEL","BFA","BGR","BHR","BDI", + "BEN","BMU","BRN","BOL","BRA","BHS","BTN","BV","BWA","BLR","BLZ","CAN","CC", + "COD","CAF","COG","CHE","CIV","COK","CHL","CMR","CHN","COL","CRI","CUB","CPV", + "CX","CYP","CZE","DEU","DJI","DNK","DMA","DOM","DZA","ECU","EST","EGY","ESH", + "ERI","ESP","ETH","FIN","FJI","FLK","FSM","FRO","FRA","FX","GAB","GBR","GRD", + "GEO","GUF","GHA","GIB","GRL","GMB","GIN","GLP","GNQ","GRC","GS","GTM","GUM", + "GNB","GUY","HKG","HM","HND","HRV","HTI","HUN","IDN","IRL","ISR","IND","IO", + "IRQ","IRN","ISL","ITA","JAM","JOR","JPN","KEN","KGZ","KHM","KIR","COM","KNA", + "PRK","KOR","KWT","CYM","KAZ","LAO","LBN","LCA","LIE","LKA","LBR","LSO","LTU", + "LUX","LVA","LBY","MAR","MCO","MDA","MDG","MHL","MKD","MLI","MMR","MNG","MAC", + "MNP","MTQ","MRT","MSR","MLT","MUS","MDV","MWI","MEX","MYS","MOZ","NAM","NCL", + "NER","NFK","NGA","NIC","NLD","NOR","NPL","NRU","NIU","NZL","OMN","PAN","PER", + "PYF","PNG","PHL","PAK","POL","SPM","PCN","PRI","PSE","PRT","PLW","PRY","QAT", + "REU","ROU","RUS","RWA","SAU","SLB","SYC","SDN","SWE","SGP","SHN","SVN","SJM", + "SVK","SLE","SMR","SEN","SOM","SUR","STP","SLV","SYR","SWZ","TCA","TCD","TF", + "TGO","THA","TJK","TKL","TLS","TKM","TUN","TON","TUR","TTO","TUV","TWN","TZA", + "UKR","UGA","UM","USA","URY","UZB","VAT","VCT","VEN","VGB","VIR","VNM","VUT", + "WLF","WSM","YEM","YT","SRB","ZAF","ZMB","MNE","ZWE","A1","A2","O1", + "ALA","GGY","IMN","JEY","BLM","MAF" + ); + + public static $COUNTRY_NAMES = array( + "", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", + "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", + "Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa", + "Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", + "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", + "Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", + "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", + "Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", + "Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook Islands", + "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde", + "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", + "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", + "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", + "Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe Islands", + "France", "France, Metropolitan", "Gabon", "United Kingdom", + "Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", + "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands", + "Guatemala", "Guam", "Guinea-Bissau", + "Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", + "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", + "British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", + "Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", + "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic People's Republic of", + "Korea, Republic of", "Kuwait", "Cayman Islands", + "Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", + "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", + "Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic of", + "Madagascar", "Marshall Islands", "Macedonia", + "Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands", + "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", + "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", + "Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", + "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia", + "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon", + "Pitcairn Islands", "Puerto Rico", "Palestinian Territory", + "Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", + "Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", + "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", + "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", + "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab Republic", + "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern Territories", + "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", + "Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu", + "Taiwan", "Tanzania, United Republic of", "Ukraine", + "Uganda", "United States Minor Outlying Islands", "United States", "Uruguay", + "Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the Grenadines", + "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", + "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", + "Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe", + "Anonymous Proxy","Satellite Provider","Other", + "Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy","Saint Martin" + ); + + // storage / caching flags + const STANDARD = 0; + const MEMORY_CACHE = 1; + const SHARED_MEMORY = 2; + + // Database structure constants + const COUNTRY_BEGIN = 16776960; + const STATE_BEGIN_REV0 = 16700000; + const STATE_BEGIN_REV1 = 16000000; + + const STRUCTURE_INFO_MAX_SIZE = 20; + const DATABASE_INFO_MAX_SIZE = 100; + const COUNTRY_EDITION = 106; + const REGION_EDITION_REV0 = 112; + const REGION_EDITION_REV1 = 3; + const CITY_EDITION_REV0 = 111; + const CITY_EDITION_REV1 = 2; + const ORG_EDITION = 110; + const SEGMENT_RECORD_LENGTH = 3; + const STANDARD_RECORD_LENGTH = 3; + const ORG_RECORD_LENGTH = 4; + const MAX_RECORD_LENGTH = 4; + const MAX_ORG_RECORD_LENGTH = 300; + const FULL_RECORD_LENGTH = 50; + + const US_OFFSET = 1; + const CANADA_OFFSET = 677; + const WORLD_OFFSET = 1353; + const FIPS_RANGE = 360; + + // SHMOP memory address + const SHM_KEY = 0x4f415401; + + /** + * @var int + */ + private $flags = 0; + + /** + * @var resource + */ + private $filehandle; + + /** + * @var string + */ + private $memoryBuffer; + + /** + * @var int + */ + private $databaseType; + + /** + * @var int + */ + private $databaseSegments; + + /** + * @var int + */ + private $recordLength; + + /** + * The memory addr "id" for use with SHMOP. + * @var int + */ + private $shmid; + + /** + * Support for singleton pattern. + * @var array + */ + private static $instances = array(); + + /** + * Construct a Net_GeoIP instance. + * You should use the getInstance() method if you plan to use multiple databases or + * the same database from several different places in your script. + * + * @param string $filename Path to binary geoip database. + * @param int $flags Flags + * + * @see getInstance() + */ + public function __construct($filename = null, $flags = null) + { + if ($filename !== null) { + $this->open($filename, $flags); + } + // store the instance, so that it will be returned by a call to + // getInstance() (with the same db filename). + self::$instances[$filename] = $this; + } + + /** + * Calls the close() function to free any resources. + * @see close() + * + * COMMENTED OUT TO ADDRESS BUG IN PHP 5.0.4, 5.0.5dev. THIS RESOURCE + * SHOULD AUTOMATICALLY BE FREED AT SCRIPT CLOSE, SO A DESTRUCTOR + * IS A GOOD IDEA BUT NOT NECESSARILY A NECESSITY. + public function __destruct() + { + $this->close(); + } + */ + + /** + * Singleton method, use this to get an instance and avoid re-parsing the db. + * + * Unique instances are instantiated based on the filename of the db. The flags + * are ignored -- in that requests to for instance with same filename but different + * flags will return the already-instantiated instance. For example: + * + * // create new instance with memory_cache enabled + * $geoip = Net_GeoIP::getInstance('C:\mydb.dat', Net_GeoIP::MEMORY_CACHE); + * .... + * + * // later in code, request instance with no flags specified. + * $geoip = Net_GeoIP::getInstance('C:\mydb.dat'); + * + * // Normally this means no MEMORY_CACHE but since an instance + * // with memory cache enabled has already been created for 'C:\mydb.dat', the + * // existing instance (with memory cache) will be returned. + * + * + * NOTE: You can only use SHARED_MEMORY flag for one instance! Any subsquent instances + * that attempt to use the SHARED_MEMORY will use the *same* shared memory, which will break + * your script. + * + * @param string $filename Filename + * @param int $flags Flags that control class behavior. + * + Net_GeoIp::SHARED_MEMORY + * Use SHMOP to share a db among multiple PHP instances. + * NOTE: ONLY ONE GEOIP INSTANCE CAN USE SHARED MEMORY!!! + * + Net_GeoIp::MEMORY_CACHE + * Store the full contents of the database in memory for current script. + * This is useful if you access the database several times in a script. + * + Net_GeoIp::STANDARD + * [default] standard no-cache version. + * + * @return Net_GeoIP + */ + public static function getInstance($filename = null, $flags = null) + { + if (!isset(self::$instances[$filename])) { + self::$instances[$filename] = new Net_GeoIP($filename, $flags); + } + return self::$instances[$filename]; + } + + /** + * Opens geoip database at filename and with specified flags. + * + * @param string $filename File to open + * @param int $flags Flags + * + * @return void + * + * @throws PEAR_Exception if unable to open specified file or shared memory. + */ + public function open($filename, $flags = null) + { + if ($flags !== null) { + $this->flags = $flags; + } + if ($this->flags & self::SHARED_MEMORY) { + $this->shmid = @shmop_open(self::SHM_KEY, "a", 0, 0); + if ($this->shmid === false) { + $this->loadSharedMemory($filename); + $this->shmid = @shmop_open(self::SHM_KEY, "a", 0, 0); + if ($this->shmid === false) { // should never be false as loadSharedMemory() will throw Exc if cannot create + throw new PEAR_Exception("Unable to open shared memory at key: " . dechex(self::SHM_KEY)); + } + } + } else { + $this->filehandle = fopen($filename, "rb"); + if (!$this->filehandle) { + throw new PEAR_Exception("Unable to open file: $filename"); + } + if ($this->flags & self::MEMORY_CACHE) { + $s_array = fstat($this->filehandle); + $this->memoryBuffer = fread($this->filehandle, $s_array['size']); + } + } + $this->setupSegments(); + } + + /** + * Loads the database file into shared memory. + * + * @param string $filename Path to database file to read into shared memory. + * + * @return void + * + * @throws PEAR_Exception - if unable to read the db file. + */ + protected function loadSharedMemory($filename) + { + $fp = fopen($filename, "rb"); + if (!$fp) { + throw new PEAR_Exception("Unable to open file: $filename"); + } + $s_array = fstat($fp); + $size = $s_array['size']; + + if ($shmid = @shmop_open(self::SHM_KEY, "w", 0, 0)) { + shmop_delete($shmid); + shmop_close($shmid); + } + + if ($shmid = @shmop_open(self::SHM_KEY, "c", 0644, $size)) { + $offset = 0; + while ($offset < $size) { + $buf = fread($fp, 524288); + shmop_write($shmid, $buf, $offset); + $offset += 524288; + } + shmop_close($shmid); + } + + fclose($fp); + } + + /** + * Parses the database file to determine what kind of database is being used and setup + * segment sizes and start points that will be used by the seek*() methods later. + * + * @return void + */ + protected function setupSegments() + { + + $this->databaseType = self::COUNTRY_EDITION; + $this->recordLength = self::STANDARD_RECORD_LENGTH; + + if ($this->flags & self::SHARED_MEMORY) { + + $offset = shmop_size($this->shmid) - 3; + for ($i = 0; $i < self::STRUCTURE_INFO_MAX_SIZE; $i++) { + $delim = shmop_read($this->shmid, $offset, 3); + $offset += 3; + if ($delim == (chr(255).chr(255).chr(255))) { + $this->databaseType = ord(shmop_read($this->shmid, $offset, 1)); + $offset++; + if ($this->databaseType === self::REGION_EDITION_REV0) { + $this->databaseSegments = self::STATE_BEGIN_REV0; + } elseif ($this->databaseType === self::REGION_EDITION_REV1) { + $this->databaseSegments = self::STATE_BEGIN_REV1; + } elseif (($this->databaseType === self::CITY_EDITION_REV0) + || ($this->databaseType === self::CITY_EDITION_REV1) + || ($this->databaseType === self::ORG_EDITION)) { + $this->databaseSegments = 0; + $buf = shmop_read($this->shmid, $offset, self::SEGMENT_RECORD_LENGTH); + for ($j = 0; $j < self::SEGMENT_RECORD_LENGTH; $j++) { + $this->databaseSegments += (ord($buf[$j]) << ($j * 8)); + } + if ($this->databaseType === self::ORG_EDITION) { + $this->recordLength = self::ORG_RECORD_LENGTH; + } + } + break; + } else { + $offset -= 4; + } + } + if ($this->databaseType == self::COUNTRY_EDITION) { + $this->databaseSegments = self::COUNTRY_BEGIN; + } + + } else { + + $filepos = ftell($this->filehandle); + fseek($this->filehandle, -3, SEEK_END); + for ($i = 0; $i < self::STRUCTURE_INFO_MAX_SIZE; $i++) { + $delim = fread($this->filehandle, 3); + if ($delim == (chr(255).chr(255).chr(255))) { + $this->databaseType = ord(fread($this->filehandle, 1)); + if ($this->databaseType === self::REGION_EDITION_REV0) { + $this->databaseSegments = self::STATE_BEGIN_REV0; + } elseif ($this->databaseType === self::REGION_EDITION_REV1) { + $this->databaseSegments = self::STATE_BEGIN_REV1; + } elseif ($this->databaseType === self::CITY_EDITION_REV0 + || $this->databaseType === self::CITY_EDITION_REV1 + || $this->databaseType === self::ORG_EDITION) { + $this->databaseSegments = 0; + $buf = fread($this->filehandle, self::SEGMENT_RECORD_LENGTH); + for ($j = 0; $j < self::SEGMENT_RECORD_LENGTH; $j++) { + $this->databaseSegments += (ord($buf[$j]) << ($j * 8)); + } + if ($this->databaseType === self::ORG_EDITION) { + $this->recordLength = self::ORG_RECORD_LENGTH; + } + } + break; + } else { + fseek($this->filehandle, -4, SEEK_CUR); + } + } + if ($this->databaseType === self::COUNTRY_EDITION) { + $this->databaseSegments = self::COUNTRY_BEGIN; + } + fseek($this->filehandle, $filepos, SEEK_SET); + + } + } + + /** + * Closes the geoip database. + * + * @return int Status of close command. + */ + public function close() + { + if ($this->flags & self::SHARED_MEMORY) { + return shmop_close($this->shmid); + } else { + // right now even if file was cached in RAM the file was not closed + // so it's safe to expect no error w/ fclose() + return fclose($this->filehandle); + } + } + + /** + * Get the country index. + * + * This method is called by the lookupCountryCode() and lookupCountryName() + * methods. It lookups up the index ('id') for the country which is the key + * for the code and name. + * + * @param string $addr IP address (hostname not allowed) + * + * @throws PEAR_Exception - if IP address is invalid. + * - if database type is incorrect + * + * @return string ID for the country + */ + protected function lookupCountryId($addr) + { + $ipnum = ip2long($addr); + if ($ipnum === false) { + throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); + } + if ($this->databaseType !== self::COUNTRY_EDITION) { + throw new PEAR_Exception("Invalid database type; lookupCountry*() methods expect Country database."); + } + return $this->seekCountry($ipnum) - self::COUNTRY_BEGIN; + } + + /** + * Returns 2-letter country code (e.g. 'CA') for specified IP address. + * Use this method if you have a Country database. + * + * @param string $addr IP address (hostname not allowed). + * + * @return string 2-letter country code + * + * @throws PEAR_Exception (see lookupCountryId()) + * @see lookupCountryId() + */ + public function lookupCountryCode($addr) + { + return self::$COUNTRY_CODES[$this->lookupCountryId($addr)]; + } + + /** + * Returns full country name for specified IP address. + * Use this method if you have a Country database. + * + * @param string $addr IP address (hostname not allowed). + * + * @return string Country name + * @throws PEAR_Exception (see lookupCountryId()) + * @see lookupCountryId() + */ + public function lookupCountryName($addr) + { + return self::$COUNTRY_NAMES[$this->lookupCountryId($addr)]; + } + + /** + * Using the record length and appropriate start points, seek to the country that corresponds + * to the converted IP address integer. + * + * @param int $ipnum Result of ip2long() conversion. + * + * @return int Offset of start of record. + * @throws PEAR_Exception - if fseek() fails on the file or no results after traversing the database (indicating corrupt db). + */ + protected function seekCountry($ipnum) + { + $offset = 0; + for ($depth = 31; $depth >= 0; --$depth) { + if ($this->flags & self::MEMORY_CACHE) { + $buf = substr($this->memoryBuffer, 2 * $this->recordLength * $offset, 2 * $this->recordLength); + } elseif ($this->flags & self::SHARED_MEMORY) { + $buf = shmop_read($this->shmid, 2 * $this->recordLength * $offset, 2 * $this->recordLength); + } else { + if (fseek($this->filehandle, 2 * $this->recordLength * $offset, SEEK_SET) !== 0) { + throw new PEAR_Exception("fseek failed"); + } + $buf = fread($this->filehandle, 2 * $this->recordLength); + } + $x = array(0,0); + for ($i = 0; $i < 2; ++$i) { + for ($j = 0; $j < $this->recordLength; ++$j) { + $x[$i] += ord($buf[$this->recordLength * $i + $j]) << ($j * 8); + } + } + if ($ipnum & (1 << $depth)) { + if ($x[1] >= $this->databaseSegments) { + return $x[1]; + } + $offset = $x[1]; + } else { + if ($x[0] >= $this->databaseSegments) { + return $x[0]; + } + $offset = $x[0]; + } + } + throw new PEAR_Exception("Error traversing database - perhaps it is corrupt?"); + } + + /** + * Lookup the organization (or ISP) for given IP address. + * Use this method if you have an Organization/ISP database. + * + * @param string $addr IP address (hostname not allowed). + * + * @throws PEAR_Exception - if IP address is invalid. + * - if database is of wrong type + * + * @return string The organization + */ + public function lookupOrg($addr) + { + $ipnum = ip2long($addr); + if ($ipnum === false) { + throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); + } + if ($this->databaseType !== self::ORG_EDITION) { + throw new PEAR_Exception("Invalid database type; lookupOrg() method expects Org/ISP database.", self::ERR_DB_FORMAT); + } + return $this->getOrg($ipnum); + } + + /** + * Lookup the region for given IP address. + * Use this method if you have a Region database. + * + * @param string $addr IP address (hostname not allowed). + * + * @return array Array containing country code and region: array($country_code, $region) + * + * @throws PEAR_Exception - if IP address is invalid. + */ + public function lookupRegion($addr) + { + $ipnum = ip2long($addr); + if ($ipnum === false) { + throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); + } + if ($this->databaseType !== self::REGION_EDITION_REV0 && $this->databaseType !== self::REGION_EDITION_REV1) { + throw new PEAR_Exception("Invalid database type; lookupRegion() method expects Region database.", self::ERR_DB_FORMAT); + } + return $this->getRegion($ipnum); + } + + /** + * Lookup the location record for given IP address. + * Use this method if you have a City database. + * + * @param string $addr IP address (hostname not allowed). + * + * @return Net_GeoIP_Location The full location record. + * + * @throws PEAR_Exception - if IP address is invalid. + */ + public function lookupLocation($addr) + { + include_once 'Net/GeoIP/Location.php'; + $ipnum = ip2long($addr); + if ($ipnum === false) { + throw new PEAR_Exception("Invalid IP address: " . var_export($addr, true), self::ERR_INVALID_IP); + } + if ($this->databaseType !== self::CITY_EDITION_REV0 && $this->databaseType !== self::CITY_EDITION_REV1) { + throw new PEAR_Exception("Invalid database type; lookupLocation() method expects City database."); + } + return $this->getRecord($ipnum); + } + + /** + * Seek and return organization (or ISP) name for converted IP addr. + * + * @param int $ipnum Converted IP address. + * + * @return string The organization + */ + protected function getOrg($ipnum) + { + $seek_org = $this->seekCountry($ipnum); + if ($seek_org == $this->databaseSegments) { + return null; + } + $record_pointer = $seek_org + (2 * $this->recordLength - 1) * $this->databaseSegments; + if ($this->flags & self::SHARED_MEMORY) { + $org_buf = shmop_read($this->shmid, $record_pointer, self::MAX_ORG_RECORD_LENGTH); + } else { + fseek($this->filehandle, $record_pointer, SEEK_SET); + $org_buf = fread($this->filehandle, self::MAX_ORG_RECORD_LENGTH); + } + $org_buf = substr($org_buf, 0, strpos($org_buf, 0)); + return $org_buf; + } + + /** + * Seek and return the region info (array containing country code and region name) for converted IP addr. + * + * @param int $ipnum Converted IP address. + * + * @return array Array containing country code and region: array($country_code, $region) + */ + protected function getRegion($ipnum) + { + if ($this->databaseType == self::REGION_EDITION_REV0) { + $seek_region = $this->seekCountry($ipnum) - self::STATE_BEGIN_REV0; + if ($seek_region >= 1000) { + $country_code = "US"; + $region = chr(($seek_region - 1000)/26 + 65) . chr(($seek_region - 1000)%26 + 65); + } else { + $country_code = self::$COUNTRY_CODES[$seek_region]; + $region = ""; + } + return array($country_code, $region); + } elseif ($this->databaseType == self::REGION_EDITION_REV1) { + $seek_region = $this->seekCountry($ipnum) - self::STATE_BEGIN_REV1; + //print $seek_region; + if ($seek_region < self::US_OFFSET) { + $country_code = ""; + $region = ""; + } elseif ($seek_region < self::CANADA_OFFSET) { + $country_code = "US"; + $region = chr(($seek_region - self::US_OFFSET)/26 + 65) . chr(($seek_region - self::US_OFFSET)%26 + 65); + } elseif ($seek_region < self::WORLD_OFFSET) { + $country_code = "CA"; + $region = chr(($seek_region - self::CANADA_OFFSET)/26 + 65) . chr(($seek_region - self::CANADA_OFFSET)%26 + 65); + } else { + $country_code = self::$COUNTRY_CODES[($seek_region - self::WORLD_OFFSET) / self::FIPS_RANGE]; + $region = ""; + } + return array ($country_code,$region); + } + } + + /** + * Seek and populate Net_GeoIP_Location object for converted IP addr. + * Note: this + * + * @param int $ipnum Converted IP address. + * + * @return Net_GeoIP_Location + */ + protected function getRecord($ipnum) + { + $seek_country = $this->seekCountry($ipnum); + if ($seek_country == $this->databaseSegments) { + return null; + } + + $record_pointer = $seek_country + (2 * $this->recordLength - 1) * $this->databaseSegments; + + if ($this->flags & self::SHARED_MEMORY) { + $record_buf = shmop_read($this->shmid, $record_pointer, self::FULL_RECORD_LENGTH); + } else { + fseek($this->filehandle, $record_pointer, SEEK_SET); + $record_buf = fread($this->filehandle, self::FULL_RECORD_LENGTH); + } + + $record = new Net_GeoIP_Location(); + + $record_buf_pos = 0; + $char = ord(substr($record_buf, $record_buf_pos, 1)); + + $record->countryCode = self::$COUNTRY_CODES[$char]; + $record->countryCode3 = self::$COUNTRY_CODES3[$char]; + $record->countryName = self::$COUNTRY_NAMES[$char]; + $record_buf_pos++; + $str_length = 0; + + //get region + $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); + while ($char != 0) { + $str_length++; + $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); + } + if ($str_length > 0) { + $record->region = substr($record_buf, $record_buf_pos, $str_length); + } + $record_buf_pos += $str_length + 1; + $str_length = 0; + + //get city + $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); + while ($char != 0) { + $str_length++; + $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); + } + if ($str_length > 0) { + $record->city = substr($record_buf, $record_buf_pos, $str_length); + } + $record_buf_pos += $str_length + 1; + $str_length = 0; + + //get postal code + $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); + while ($char != 0) { + $str_length++; + $char = ord(substr($record_buf, $record_buf_pos+$str_length, 1)); + } + if ($str_length > 0) { + $record->postalCode = substr($record_buf, $record_buf_pos, $str_length); + } + $record_buf_pos += $str_length + 1; + $str_length = 0; + $latitude = 0; + $longitude = 0; + for ($j = 0;$j < 3; ++$j) { + $char = ord(substr($record_buf, $record_buf_pos++, 1)); + $latitude += ($char << ($j * 8)); + } + $record->latitude = ($latitude/10000) - 180; + + for ($j = 0;$j < 3; ++$j) { + $char = ord(substr($record_buf, $record_buf_pos++, 1)); + $longitude += ($char << ($j * 8)); + } + $record->longitude = ($longitude/10000) - 180; + + if ($this->databaseType === self::CITY_EDITION_REV1) { + $dmaarea_combo = 0; + if ($record->countryCode == "US") { + for ($j = 0;$j < 3;++$j) { + $char = ord(substr($record_buf, $record_buf_pos++, 1)); + $dmaarea_combo += ($char << ($j * 8)); + } + $record->dmaCode = floor($dmaarea_combo/1000); + $record->areaCode = $dmaarea_combo%1000; + } + } + + return $record; + } + +} + diff --git a/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/DMA.php b/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/DMA.php index 44a01e200..58d00d74f 100644 --- a/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/DMA.php +++ b/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/DMA.php @@ -1,315 +1,315 @@ - (original Maxmind version) | - * | Hans Lellelid | - * +----------------------------------------------------------------------+ - * - * @category Net - * @package Net_GeoIP - * @author Hans Lellelid - * @license LGPL http://www.gnu.org/licenses/lgpl.txt - * @link http://pear.php.net/package/Net_GeoIp - * $Id: DMA.php 296755 2010-03-24 22:22:06Z clockwerx $ - */ - -/** - * Static class to handle mapping of DMA codes to metro regions. - * - * Use this class with the dmaCode property of the Net_GeoIpLocation object. - * - * - * $region = Net_GeoIPDMA::getMetroRegion($record->dmaCode); - * - * - * @category Net - * @package Net_GeoIP - * @author Hans Lellelid - * @author Dmitri Snytkine - * @license LGPL http://www.gnu.org/licenses/lgpl.txt - * @version $Revision: 296755 $ - * @link http://pear.php.net/package/Net_GeoIp - */ -class Net_GeoIP_DMA -{ - /** - * Holds DMA -> Metro mapping. - * @var array - */ - private static $dmaMap; - - /** - * Initialize - * - * @return void - */ - public static function initialize() - { - self::$dmaMap = array( - 500 => 'Portland-Auburn, ME', - 501 => 'New York, NY', - 502 => 'Binghamton, NY', - 503 => 'Macon, GA', - 504 => 'Philadelphia, PA', - 505 => 'Detroit, MI', - 506 => 'Boston, MA', - 507 => 'Savannah, GA', - 508 => 'Pittsburgh, PA', - 509 => 'Ft Wayne, IN', - 510 => 'Cleveland, OH', - 511 => 'Washington, DC', - 512 => 'Baltimore, MD', - 513 => 'Flint, MI', - 514 => 'Buffalo, NY', - 515 => 'Cincinnati, OH', - 516 => 'Erie, PA', - 517 => 'Charlotte, NC', - 518 => 'Greensboro, NC', - 519 => 'Charleston, SC', - 520 => 'Augusta, GA', - 521 => 'Providence, RI', - 522 => 'Columbus, GA', - 523 => 'Burlington, VT', - 524 => 'Atlanta, GA', - 525 => 'Albany, GA', - 526 => 'Utica-Rome, NY', - 527 => 'Indianapolis, IN', - 528 => 'Miami, FL', - 529 => 'Louisville, KY', - 530 => 'Tallahassee, FL', - 531 => 'Tri-Cities, TN', - 532 => 'Albany-Schenectady-Troy, NY', - 533 => 'Hartford, CT', - 534 => 'Orlando, FL', - 535 => 'Columbus, OH', - 536 => 'Youngstown-Warren, OH', - 537 => 'Bangor, ME', - 538 => 'Rochester, NY', - 539 => 'Tampa, FL', - 540 => 'Traverse City-Cadillac, MI', - 541 => 'Lexington, KY', - 542 => 'Dayton, OH', - 543 => 'Springfield-Holyoke, MA', - 544 => 'Norfolk-Portsmouth, VA', - 545 => 'Greenville-New Bern-Washington, NC', - 546 => 'Columbia, SC', - 547 => 'Toledo, OH', - 548 => 'West Palm Beach, FL', - 549 => 'Watertown, NY', - 550 => 'Wilmington, NC', - 551 => 'Lansing, MI', - 552 => 'Presque Isle, ME', - 553 => 'Marquette, MI', - 554 => 'Wheeling, WV', - 555 => 'Syracuse, NY', - 556 => 'Richmond-Petersburg, VA', - 557 => 'Knoxville, TN', - 558 => 'Lima, OH', - 559 => 'Bluefield-Beckley-Oak Hill, WV', - 560 => 'Raleigh-Durham, NC', - 561 => 'Jacksonville, FL', - 563 => 'Grand Rapids, MI', - 564 => 'Charleston-Huntington, WV', - 565 => 'Elmira, NY', - 566 => 'Harrisburg-Lancaster-Lebanon-York, PA', - 567 => 'Greenville-Spartenburg, SC', - 569 => 'Harrisonburg, VA', - 570 => 'Florence-Myrtle Beach, SC', - 571 => 'Ft Myers, FL', - 573 => 'Roanoke-Lynchburg, VA', - 574 => 'Johnstown-Altoona, PA', - 575 => 'Chattanooga, TN', - 576 => 'Salisbury, MD', - 577 => 'Wilkes Barre-Scranton, PA', - 581 => 'Terre Haute, IN', - 582 => 'Lafayette, IN', - 583 => 'Alpena, MI', - 584 => 'Charlottesville, VA', - 588 => 'South Bend, IN', - 592 => 'Gainesville, FL', - 596 => 'Zanesville, OH', - 597 => 'Parkersburg, WV', - 598 => 'Clarksburg-Weston, WV', - 600 => 'Corpus Christi, TX', - 602 => 'Chicago, IL', - 603 => 'Joplin-Pittsburg, MO', - 604 => 'Columbia-Jefferson City, MO', - 605 => 'Topeka, KS', - 606 => 'Dothan, AL', - 609 => 'St Louis, MO', - 610 => 'Rockford, IL', - 611 => 'Rochester-Mason City-Austin, MN', - 612 => 'Shreveport, LA', - 613 => 'Minneapolis-St Paul, MN', - 616 => 'Kansas City, MO', - 617 => 'Milwaukee, WI', - 618 => 'Houston, TX', - 619 => 'Springfield, MO', - 620 => 'Tuscaloosa, AL', - 622 => 'New Orleans, LA', - 623 => 'Dallas-Fort Worth, TX', - 624 => 'Sioux City, IA', - 625 => 'Waco-Temple-Bryan, TX', - 626 => 'Victoria, TX', - 627 => 'Wichita Falls, TX', - 628 => 'Monroe, LA', - 630 => 'Birmingham, AL', - 631 => 'Ottumwa-Kirksville, IA', - 632 => 'Paducah, KY', - 633 => 'Odessa-Midland, TX', - 634 => 'Amarillo, TX', - 635 => 'Austin, TX', - 636 => 'Harlingen, TX', - 637 => 'Cedar Rapids-Waterloo, IA', - 638 => 'St Joseph, MO', - 639 => 'Jackson, TN', - 640 => 'Memphis, TN', - 641 => 'San Antonio, TX', - 642 => 'Lafayette, LA', - 643 => 'Lake Charles, LA', - 644 => 'Alexandria, LA', - 646 => 'Anniston, AL', - 647 => 'Greenwood-Greenville, MS', - 648 => 'Champaign-Springfield-Decatur, IL', - 649 => 'Evansville, IN', - 650 => 'Oklahoma City, OK', - 651 => 'Lubbock, TX', - 652 => 'Omaha, NE', - 656 => 'Panama City, FL', - 657 => 'Sherman, TX', - 658 => 'Green Bay-Appleton, WI', - 659 => 'Nashville, TN', - 661 => 'San Angelo, TX', - 662 => 'Abilene-Sweetwater, TX', - 669 => 'Madison, WI', - 670 => 'Ft Smith-Fay-Springfield, AR', - 671 => 'Tulsa, OK', - 673 => 'Columbus-Tupelo-West Point, MS', - 675 => 'Peoria-Bloomington, IL', - 676 => 'Duluth, MN', - 678 => 'Wichita, KS', - 679 => 'Des Moines, IA', - 682 => 'Davenport-Rock Island-Moline, IL', - 686 => 'Mobile, AL', - 687 => 'Minot-Bismarck-Dickinson, ND', - 691 => 'Huntsville, AL', - 692 => 'Beaumont-Port Author, TX', - 693 => 'Little Rock-Pine Bluff, AR', - 698 => 'Montgomery, AL', - 702 => 'La Crosse-Eau Claire, WI', - 705 => 'Wausau-Rhinelander, WI', - 709 => 'Tyler-Longview, TX', - 710 => 'Hattiesburg-Laurel, MS', - 711 => 'Meridian, MS', - 716 => 'Baton Rouge, LA', - 717 => 'Quincy, IL', - 718 => 'Jackson, MS', - 722 => 'Lincoln-Hastings, NE', - 724 => 'Fargo-Valley City, ND', - 725 => 'Sioux Falls, SD', - 734 => 'Jonesboro, AR', - 736 => 'Bowling Green, KY', - 737 => 'Mankato, MN', - 740 => 'North Platte, NE', - 743 => 'Anchorage, AK', - 744 => 'Honolulu, HI', - 745 => 'Fairbanks, AK', - 746 => 'Biloxi-Gulfport, MS', - 747 => 'Juneau, AK', - 749 => 'Laredo, TX', - 751 => 'Denver, CO', - 752 => 'Colorado Springs, CO', - 753 => 'Phoenix, AZ', - 754 => 'Butte-Bozeman, MT', - 755 => 'Great Falls, MT', - 756 => 'Billings, MT', - 757 => 'Boise, ID', - 758 => 'Idaho Falls-Pocatello, ID', - 759 => 'Cheyenne, WY', - 760 => 'Twin Falls, ID', - 762 => 'Missoula, MT', - 764 => 'Rapid City, SD', - 765 => 'El Paso, TX', - 766 => 'Helena, MT', - 767 => 'Casper-Riverton, WY', - 770 => 'Salt Lake City, UT', - 771 => 'Yuma, AZ', - 773 => 'Grand Junction, CO', - 789 => 'Tucson, AZ', - 790 => 'Albuquerque, NM', - 798 => 'Glendive, MT', - 800 => 'Bakersfield, CA', - 801 => 'Eugene, OR', - 802 => 'Eureka, CA', - 803 => 'Los Angeles, CA', - 804 => 'Palm Springs, CA', - 807 => 'San Francisco, CA', - 810 => 'Yakima-Pasco, WA', - 811 => 'Reno, NV', - 813 => 'Medford-Klamath Falls, OR', - 819 => 'Seattle-Tacoma, WA', - 820 => 'Portland, OR', - 821 => 'Bend, OR', - 825 => 'San Diego, CA', - 828 => 'Monterey-Salinas, CA', - 839 => 'Las Vegas, NV', - 855 => 'Santa Barbara, CA', - 862 => 'Sacramento, CA', - 866 => 'Fresno, CA', - 868 => 'Chico-Redding, CA', - 881 => 'Spokane, WA'); - } - - /** - * Lookup the metro region based on the provided DMA code. - * - * @param int $dmaCode The DMA code - * - * @return string Metro region name. - */ - public static function getMetroRegion($dmaCode) - { - if ($dmaCode === null) { - return null; - } - if (self::$dmaMap === null) { - self::initialize(); - } - return self::$dmaMap[$dmaCode]; - } - - /** - * Reverse lookup of DMA code if [exact] metro region name is known. - * - * @param string $metro Metro region name. - * - * @return int DMA code, or false if not found. - */ - public static function getDMACode($metro) - { - if (self::$dmaMap === null) { - self::initialize(); - } - return array_search($metro, self::$dmaMap); - } - + (original Maxmind version) | + * | Hans Lellelid | + * +----------------------------------------------------------------------+ + * + * @category Net + * @package Net_GeoIP + * @author Hans Lellelid + * @license LGPL http://www.gnu.org/licenses/lgpl.txt + * @link http://pear.php.net/package/Net_GeoIp + * $Id: DMA.php 296755 2010-03-24 22:22:06Z clockwerx $ + */ + +/** + * Static class to handle mapping of DMA codes to metro regions. + * + * Use this class with the dmaCode property of the Net_GeoIpLocation object. + * + * + * $region = Net_GeoIPDMA::getMetroRegion($record->dmaCode); + * + * + * @category Net + * @package Net_GeoIP + * @author Hans Lellelid + * @author Dmitri Snytkine + * @license LGPL http://www.gnu.org/licenses/lgpl.txt + * @version $Revision: 296755 $ + * @link http://pear.php.net/package/Net_GeoIp + */ +class Net_GeoIP_DMA +{ + /** + * Holds DMA -> Metro mapping. + * @var array + */ + private static $dmaMap; + + /** + * Initialize + * + * @return void + */ + public static function initialize() + { + self::$dmaMap = array( + 500 => 'Portland-Auburn, ME', + 501 => 'New York, NY', + 502 => 'Binghamton, NY', + 503 => 'Macon, GA', + 504 => 'Philadelphia, PA', + 505 => 'Detroit, MI', + 506 => 'Boston, MA', + 507 => 'Savannah, GA', + 508 => 'Pittsburgh, PA', + 509 => 'Ft Wayne, IN', + 510 => 'Cleveland, OH', + 511 => 'Washington, DC', + 512 => 'Baltimore, MD', + 513 => 'Flint, MI', + 514 => 'Buffalo, NY', + 515 => 'Cincinnati, OH', + 516 => 'Erie, PA', + 517 => 'Charlotte, NC', + 518 => 'Greensboro, NC', + 519 => 'Charleston, SC', + 520 => 'Augusta, GA', + 521 => 'Providence, RI', + 522 => 'Columbus, GA', + 523 => 'Burlington, VT', + 524 => 'Atlanta, GA', + 525 => 'Albany, GA', + 526 => 'Utica-Rome, NY', + 527 => 'Indianapolis, IN', + 528 => 'Miami, FL', + 529 => 'Louisville, KY', + 530 => 'Tallahassee, FL', + 531 => 'Tri-Cities, TN', + 532 => 'Albany-Schenectady-Troy, NY', + 533 => 'Hartford, CT', + 534 => 'Orlando, FL', + 535 => 'Columbus, OH', + 536 => 'Youngstown-Warren, OH', + 537 => 'Bangor, ME', + 538 => 'Rochester, NY', + 539 => 'Tampa, FL', + 540 => 'Traverse City-Cadillac, MI', + 541 => 'Lexington, KY', + 542 => 'Dayton, OH', + 543 => 'Springfield-Holyoke, MA', + 544 => 'Norfolk-Portsmouth, VA', + 545 => 'Greenville-New Bern-Washington, NC', + 546 => 'Columbia, SC', + 547 => 'Toledo, OH', + 548 => 'West Palm Beach, FL', + 549 => 'Watertown, NY', + 550 => 'Wilmington, NC', + 551 => 'Lansing, MI', + 552 => 'Presque Isle, ME', + 553 => 'Marquette, MI', + 554 => 'Wheeling, WV', + 555 => 'Syracuse, NY', + 556 => 'Richmond-Petersburg, VA', + 557 => 'Knoxville, TN', + 558 => 'Lima, OH', + 559 => 'Bluefield-Beckley-Oak Hill, WV', + 560 => 'Raleigh-Durham, NC', + 561 => 'Jacksonville, FL', + 563 => 'Grand Rapids, MI', + 564 => 'Charleston-Huntington, WV', + 565 => 'Elmira, NY', + 566 => 'Harrisburg-Lancaster-Lebanon-York, PA', + 567 => 'Greenville-Spartenburg, SC', + 569 => 'Harrisonburg, VA', + 570 => 'Florence-Myrtle Beach, SC', + 571 => 'Ft Myers, FL', + 573 => 'Roanoke-Lynchburg, VA', + 574 => 'Johnstown-Altoona, PA', + 575 => 'Chattanooga, TN', + 576 => 'Salisbury, MD', + 577 => 'Wilkes Barre-Scranton, PA', + 581 => 'Terre Haute, IN', + 582 => 'Lafayette, IN', + 583 => 'Alpena, MI', + 584 => 'Charlottesville, VA', + 588 => 'South Bend, IN', + 592 => 'Gainesville, FL', + 596 => 'Zanesville, OH', + 597 => 'Parkersburg, WV', + 598 => 'Clarksburg-Weston, WV', + 600 => 'Corpus Christi, TX', + 602 => 'Chicago, IL', + 603 => 'Joplin-Pittsburg, MO', + 604 => 'Columbia-Jefferson City, MO', + 605 => 'Topeka, KS', + 606 => 'Dothan, AL', + 609 => 'St Louis, MO', + 610 => 'Rockford, IL', + 611 => 'Rochester-Mason City-Austin, MN', + 612 => 'Shreveport, LA', + 613 => 'Minneapolis-St Paul, MN', + 616 => 'Kansas City, MO', + 617 => 'Milwaukee, WI', + 618 => 'Houston, TX', + 619 => 'Springfield, MO', + 620 => 'Tuscaloosa, AL', + 622 => 'New Orleans, LA', + 623 => 'Dallas-Fort Worth, TX', + 624 => 'Sioux City, IA', + 625 => 'Waco-Temple-Bryan, TX', + 626 => 'Victoria, TX', + 627 => 'Wichita Falls, TX', + 628 => 'Monroe, LA', + 630 => 'Birmingham, AL', + 631 => 'Ottumwa-Kirksville, IA', + 632 => 'Paducah, KY', + 633 => 'Odessa-Midland, TX', + 634 => 'Amarillo, TX', + 635 => 'Austin, TX', + 636 => 'Harlingen, TX', + 637 => 'Cedar Rapids-Waterloo, IA', + 638 => 'St Joseph, MO', + 639 => 'Jackson, TN', + 640 => 'Memphis, TN', + 641 => 'San Antonio, TX', + 642 => 'Lafayette, LA', + 643 => 'Lake Charles, LA', + 644 => 'Alexandria, LA', + 646 => 'Anniston, AL', + 647 => 'Greenwood-Greenville, MS', + 648 => 'Champaign-Springfield-Decatur, IL', + 649 => 'Evansville, IN', + 650 => 'Oklahoma City, OK', + 651 => 'Lubbock, TX', + 652 => 'Omaha, NE', + 656 => 'Panama City, FL', + 657 => 'Sherman, TX', + 658 => 'Green Bay-Appleton, WI', + 659 => 'Nashville, TN', + 661 => 'San Angelo, TX', + 662 => 'Abilene-Sweetwater, TX', + 669 => 'Madison, WI', + 670 => 'Ft Smith-Fay-Springfield, AR', + 671 => 'Tulsa, OK', + 673 => 'Columbus-Tupelo-West Point, MS', + 675 => 'Peoria-Bloomington, IL', + 676 => 'Duluth, MN', + 678 => 'Wichita, KS', + 679 => 'Des Moines, IA', + 682 => 'Davenport-Rock Island-Moline, IL', + 686 => 'Mobile, AL', + 687 => 'Minot-Bismarck-Dickinson, ND', + 691 => 'Huntsville, AL', + 692 => 'Beaumont-Port Author, TX', + 693 => 'Little Rock-Pine Bluff, AR', + 698 => 'Montgomery, AL', + 702 => 'La Crosse-Eau Claire, WI', + 705 => 'Wausau-Rhinelander, WI', + 709 => 'Tyler-Longview, TX', + 710 => 'Hattiesburg-Laurel, MS', + 711 => 'Meridian, MS', + 716 => 'Baton Rouge, LA', + 717 => 'Quincy, IL', + 718 => 'Jackson, MS', + 722 => 'Lincoln-Hastings, NE', + 724 => 'Fargo-Valley City, ND', + 725 => 'Sioux Falls, SD', + 734 => 'Jonesboro, AR', + 736 => 'Bowling Green, KY', + 737 => 'Mankato, MN', + 740 => 'North Platte, NE', + 743 => 'Anchorage, AK', + 744 => 'Honolulu, HI', + 745 => 'Fairbanks, AK', + 746 => 'Biloxi-Gulfport, MS', + 747 => 'Juneau, AK', + 749 => 'Laredo, TX', + 751 => 'Denver, CO', + 752 => 'Colorado Springs, CO', + 753 => 'Phoenix, AZ', + 754 => 'Butte-Bozeman, MT', + 755 => 'Great Falls, MT', + 756 => 'Billings, MT', + 757 => 'Boise, ID', + 758 => 'Idaho Falls-Pocatello, ID', + 759 => 'Cheyenne, WY', + 760 => 'Twin Falls, ID', + 762 => 'Missoula, MT', + 764 => 'Rapid City, SD', + 765 => 'El Paso, TX', + 766 => 'Helena, MT', + 767 => 'Casper-Riverton, WY', + 770 => 'Salt Lake City, UT', + 771 => 'Yuma, AZ', + 773 => 'Grand Junction, CO', + 789 => 'Tucson, AZ', + 790 => 'Albuquerque, NM', + 798 => 'Glendive, MT', + 800 => 'Bakersfield, CA', + 801 => 'Eugene, OR', + 802 => 'Eureka, CA', + 803 => 'Los Angeles, CA', + 804 => 'Palm Springs, CA', + 807 => 'San Francisco, CA', + 810 => 'Yakima-Pasco, WA', + 811 => 'Reno, NV', + 813 => 'Medford-Klamath Falls, OR', + 819 => 'Seattle-Tacoma, WA', + 820 => 'Portland, OR', + 821 => 'Bend, OR', + 825 => 'San Diego, CA', + 828 => 'Monterey-Salinas, CA', + 839 => 'Las Vegas, NV', + 855 => 'Santa Barbara, CA', + 862 => 'Sacramento, CA', + 866 => 'Fresno, CA', + 868 => 'Chico-Redding, CA', + 881 => 'Spokane, WA'); + } + + /** + * Lookup the metro region based on the provided DMA code. + * + * @param int $dmaCode The DMA code + * + * @return string Metro region name. + */ + public static function getMetroRegion($dmaCode) + { + if ($dmaCode === null) { + return null; + } + if (self::$dmaMap === null) { + self::initialize(); + } + return self::$dmaMap[$dmaCode]; + } + + /** + * Reverse lookup of DMA code if [exact] metro region name is known. + * + * @param string $metro Metro region name. + * + * @return int DMA code, or false if not found. + */ + public static function getDMACode($metro) + { + if (self::$dmaMap === null) { + self::initialize(); + } + return array_search($metro, self::$dmaMap); + } + } \ No newline at end of file diff --git a/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/Location.php b/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/Location.php index 8da0a5bb2..39ba992a4 100644 --- a/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/Location.php +++ b/modules/maxmind_geoip/includes/Net_GeoIP-1.0.0RC3/Net/GeoIP/Location.php @@ -1,201 +1,201 @@ - (original Maxmind version) | - * | Hans Lellelid | - * +----------------------------------------------------------------------+ - * - * @category Net - * @package Net_GeoIP - * @author Hans Lellelid - * @license LGPL http://www.gnu.org/licenses/lgpl.txt - * @link http://pear.php.net/package/Net_GeoIp - * $Id: Location.php 296763 2010-03-25 00:53:44Z clockwerx $ - */ - -/** - * This class represents a location record as returned by Net_GeoIP::lookupLocation(). - * - * This class is primarily a collection of values (the public properties of the class), but - * there is also a distance() method to calculate the km distance between two points. - * - * @category Net - * @package Net_GeoIP - * @author Hans Lellelid - * @author Dmitri Snytkine - * @license LGPL http://www.gnu.org/licenses/lgpl.txt - * @version $Revision: 296763 $ - * @link http://pear.php.net/package/Net_GeoIp - * @see Net_GeoIP::lookupLocation() - */ -class Net_GeoIP_Location implements Serializable -{ - protected $aData = array( - 'countryCode' => null, - 'countryCode3' => null, - 'countryName' => null, - 'region' => null, - 'city' => null, - 'postalCode' => null, - 'latitude' => null, - 'longitude' => null, - 'areaCode' => null, - 'dmaCode' => null - ); - - - /** - * Calculate the distance in km between two points. - * - * @param Net_GeoIP_Location $loc The other point to which distance will be calculated. - * - * @return float The number of km between two points on the globe. - */ - public function distance(Net_GeoIP_Location $loc) - { - // ideally these should be class constants, but class constants - // can't be operations. - $RAD_CONVERT = M_PI / 180; - $EARTH_DIAMETER = 2 * 6378.2; - - $lat1 = $this->latitude; - $lon1 = $this->longitude; - $lat2 = $loc->latitude; - $lon2 = $loc->longitude; - - // convert degrees to radians - $lat1 *= $RAD_CONVERT; - $lat2 *= $RAD_CONVERT; - - // find the deltas - $delta_lat = $lat2 - $lat1; - $delta_lon = ($lon2 - $lon1) * $RAD_CONVERT; - - // Find the great circle distance - $temp = pow(sin($delta_lat/2), 2) + cos($lat1) * cos($lat2) * pow(sin($delta_lon/2), 2); - return $EARTH_DIAMETER * atan2(sqrt($temp), sqrt(1-$temp)); - } - - /** - * magic method to make it possible - * to store this object in cache when - * automatic serialization is on - * Specifically it makes it possible to store - * this object in memcache - * - * @return array - */ - public function serialize() - { - return serialize($this->aData); - } - - /** - * unserialize a representation of the object - * - * @param array $serialized The serialized representation of the location - * - * @return void - */ - public function unserialize($serialized) - { - $this->aData = unserialize($serialized); - } - - - /** - * Setter for elements of $this->aData array - * - * @param string $name The variable to set - * @param string $val The value - * - * @return object $this object - */ - public function set($name, $val) - { - if (array_key_exists($name, $this->aData)) { - $this->aData[$name] = $val; - } - - return $this; - } - - public function __set($name, $val) - { - return $this->set($name, $val); - } - - /** - * Getter for $this->aData array - * - * @return array - */ - public function getData() - { - return $this->aData; - } - - - /** - * Magic method to get value from $this->aData array - * - * @param string $name The var to get - * - * @return mixed string if value exists or null if it is empty of - * just does not exist - */ - public function __get($name) - { - if (array_key_exists($name, $this->aData)) { - return $this->aData[$name]; - } - - return null; - } - - - /** - * String representation of the object - * - * @return string text and result of print_r of $this->aData array - */ - public function __toString() - { - return 'object of type '.__CLASS__.'. data: '.implode(',', $this->aData); - } - - - /** - * Magic method - * makes it possible to check if specific record exists - * and also makes it possible to use empty() on any property - * - * @param strign $name The name of the var to check - * - * @return bool - */ - public function __isset($name) - { - return (null !== $this->__get($name)); - } - -} + (original Maxmind version) | + * | Hans Lellelid | + * +----------------------------------------------------------------------+ + * + * @category Net + * @package Net_GeoIP + * @author Hans Lellelid + * @license LGPL http://www.gnu.org/licenses/lgpl.txt + * @link http://pear.php.net/package/Net_GeoIp + * $Id: Location.php 296763 2010-03-25 00:53:44Z clockwerx $ + */ + +/** + * This class represents a location record as returned by Net_GeoIP::lookupLocation(). + * + * This class is primarily a collection of values (the public properties of the class), but + * there is also a distance() method to calculate the km distance between two points. + * + * @category Net + * @package Net_GeoIP + * @author Hans Lellelid + * @author Dmitri Snytkine + * @license LGPL http://www.gnu.org/licenses/lgpl.txt + * @version $Revision: 296763 $ + * @link http://pear.php.net/package/Net_GeoIp + * @see Net_GeoIP::lookupLocation() + */ +class Net_GeoIP_Location implements Serializable +{ + protected $aData = array( + 'countryCode' => null, + 'countryCode3' => null, + 'countryName' => null, + 'region' => null, + 'city' => null, + 'postalCode' => null, + 'latitude' => null, + 'longitude' => null, + 'areaCode' => null, + 'dmaCode' => null + ); + + + /** + * Calculate the distance in km between two points. + * + * @param Net_GeoIP_Location $loc The other point to which distance will be calculated. + * + * @return float The number of km between two points on the globe. + */ + public function distance(Net_GeoIP_Location $loc) + { + // ideally these should be class constants, but class constants + // can't be operations. + $RAD_CONVERT = M_PI / 180; + $EARTH_DIAMETER = 2 * 6378.2; + + $lat1 = $this->latitude; + $lon1 = $this->longitude; + $lat2 = $loc->latitude; + $lon2 = $loc->longitude; + + // convert degrees to radians + $lat1 *= $RAD_CONVERT; + $lat2 *= $RAD_CONVERT; + + // find the deltas + $delta_lat = $lat2 - $lat1; + $delta_lon = ($lon2 - $lon1) * $RAD_CONVERT; + + // Find the great circle distance + $temp = pow(sin($delta_lat/2), 2) + cos($lat1) * cos($lat2) * pow(sin($delta_lon/2), 2); + return $EARTH_DIAMETER * atan2(sqrt($temp), sqrt(1-$temp)); + } + + /** + * magic method to make it possible + * to store this object in cache when + * automatic serialization is on + * Specifically it makes it possible to store + * this object in memcache + * + * @return array + */ + public function serialize() + { + return serialize($this->aData); + } + + /** + * unserialize a representation of the object + * + * @param array $serialized The serialized representation of the location + * + * @return void + */ + public function unserialize($serialized) + { + $this->aData = unserialize($serialized); + } + + + /** + * Setter for elements of $this->aData array + * + * @param string $name The variable to set + * @param string $val The value + * + * @return object $this object + */ + public function set($name, $val) + { + if (array_key_exists($name, $this->aData)) { + $this->aData[$name] = $val; + } + + return $this; + } + + public function __set($name, $val) + { + return $this->set($name, $val); + } + + /** + * Getter for $this->aData array + * + * @return array + */ + public function getData() + { + return $this->aData; + } + + + /** + * Magic method to get value from $this->aData array + * + * @param string $name The var to get + * + * @return mixed string if value exists or null if it is empty of + * just does not exist + */ + public function __get($name) + { + if (array_key_exists($name, $this->aData)) { + return $this->aData[$name]; + } + + return null; + } + + + /** + * String representation of the object + * + * @return string text and result of print_r of $this->aData array + */ + public function __toString() + { + return 'object of type '.__CLASS__.'. data: '.implode(',', $this->aData); + } + + + /** + * Magic method + * makes it possible to check if specific record exists + * and also makes it possible to use empty() on any property + * + * @param strign $name The name of the var to check + * + * @return bool + */ + public function __isset($name) + { + return (null !== $this->__get($name)); + } + +} diff --git a/modules/maxmind_geoip/includes/maxmind-ws/GeoCityLocateIspOrg.class.php b/modules/maxmind_geoip/includes/maxmind-ws/GeoCityLocateIspOrg.class.php index cf8ce616c..338e78278 100755 --- a/modules/maxmind_geoip/includes/maxmind-ws/GeoCityLocateIspOrg.class.php +++ b/modules/maxmind_geoip/includes/maxmind-ws/GeoCityLocateIspOrg.class.php @@ -1,224 +1,224 @@ - - * - */ - class GeoCityLocateIspOrg extends MaxMindWebServices { - - /** - * Implements a singleton design pattern - * - * when looking for an instance one can pass an IP address to have data populated - * - * @access public - * @param string - * @return reference to a GeoCityLocateIspOrg object - */ - function &getInstance($ip = "") { - static $instance = null; - - if ($instance === null) { - $instance = new GeoCityLocateIspOrg(); - } - - if(!empty($ip)){ - $instance->setIP($ip); - } - - return $instance; - } - - /** - * An array that holds all returned values from a Maxmind request - * - * @param string - * @access public - */ - function setIP($ip){ - $this->data = array(); - $this->ip = $ip; - $this->_process(); - } - - /** - * Get the IP address that is being processed - * - * @return string - * @access public - */ - function getIP(){ - return $this->ip; - } - - /** - * Get the return Country Code - * - * @return string - * @access public - */ - function getCountryCode(){ - return $this->data[0]; - } - - /** - * Get the return Region Code - * - * @return string - * @access public - */ - function getRegion(){ - return $this->data[1]; - } - - /** - * Get the return Region Code - * - * @return string - * @access public - */ - function getState(){ - return $this->getRegion(); - } - - /** - * Get the return City - * - * @return string - * @access public - */ - function getCity(){ - return $this->data[2]; - } - - /** - * Get the return Postal - * - * @return string - * @access public - */ - function getPostal(){ - return $this->data[3]; - } - - /** - * Get the return Postal - * - * @return string - * @access public - */ - function getZip(){ - return $this->getPostal(); - } - - /** - * Get the return Latitude - * - * @return string - * @access public - */ - function getLatitude(){ - return $this->data[4]; - } - - /** - * Get the return Latitude - * - * @return string - * @access public - */ - function getLat(){ - return $this->getLatitude(); - } - - /** - * Get the return Longitude - * - * @return string - * @access public - */ - function getLongitude(){ - return $this->data[5]; - } - - /** - * Get the return Longitude - * - * @return string - * @access public - */ - function getLong(){ - return $this->getLongitude(); - } - - /** - * Get the return Metro Code - * - * @return string - * @access public - */ - function getMetroCode(){ - return $this->data[6]; - } - - /** - * Get the return Area Code - * - * @return string - * @access public - */ - function getAreaCode(){ - return $this->data[7]; - } - - /** - * Get the return ISP - * - * @return string - * @access public - */ - function getISP(){ - return $this->data[8]; - } - - /** - * Get the return Organization - * - * @return string - * @access public - */ - function getOrganization(){ - return $this->data[9]; - } - - /** - * Get the return Error - * - * @return string - * @access public - */ - function getError(){ - return $this->data[10]; - - } - - /** - * Formats the url to submit to Maxmind and returns data in an array - * - * @access private - */ - function _process(){ - $url = "http://maxmind.com:8010/f?l=" . $this->licenceKey . "&i=" . $this->ip; - $response = $this->_queryMaxMind($url); - $this->data = $this->csv_split( trim($response) ); - } - - - } - + + * + */ + class GeoCityLocateIspOrg extends MaxMindWebServices { + + /** + * Implements a singleton design pattern + * + * when looking for an instance one can pass an IP address to have data populated + * + * @access public + * @param string + * @return reference to a GeoCityLocateIspOrg object + */ + function &getInstance($ip = "") { + static $instance = null; + + if ($instance === null) { + $instance = new GeoCityLocateIspOrg(); + } + + if(!empty($ip)){ + $instance->setIP($ip); + } + + return $instance; + } + + /** + * An array that holds all returned values from a Maxmind request + * + * @param string + * @access public + */ + function setIP($ip){ + $this->data = array(); + $this->ip = $ip; + $this->_process(); + } + + /** + * Get the IP address that is being processed + * + * @return string + * @access public + */ + function getIP(){ + return $this->ip; + } + + /** + * Get the return Country Code + * + * @return string + * @access public + */ + function getCountryCode(){ + return $this->data[0]; + } + + /** + * Get the return Region Code + * + * @return string + * @access public + */ + function getRegion(){ + return $this->data[1]; + } + + /** + * Get the return Region Code + * + * @return string + * @access public + */ + function getState(){ + return $this->getRegion(); + } + + /** + * Get the return City + * + * @return string + * @access public + */ + function getCity(){ + return $this->data[2]; + } + + /** + * Get the return Postal + * + * @return string + * @access public + */ + function getPostal(){ + return $this->data[3]; + } + + /** + * Get the return Postal + * + * @return string + * @access public + */ + function getZip(){ + return $this->getPostal(); + } + + /** + * Get the return Latitude + * + * @return string + * @access public + */ + function getLatitude(){ + return $this->data[4]; + } + + /** + * Get the return Latitude + * + * @return string + * @access public + */ + function getLat(){ + return $this->getLatitude(); + } + + /** + * Get the return Longitude + * + * @return string + * @access public + */ + function getLongitude(){ + return $this->data[5]; + } + + /** + * Get the return Longitude + * + * @return string + * @access public + */ + function getLong(){ + return $this->getLongitude(); + } + + /** + * Get the return Metro Code + * + * @return string + * @access public + */ + function getMetroCode(){ + return $this->data[6]; + } + + /** + * Get the return Area Code + * + * @return string + * @access public + */ + function getAreaCode(){ + return $this->data[7]; + } + + /** + * Get the return ISP + * + * @return string + * @access public + */ + function getISP(){ + return $this->data[8]; + } + + /** + * Get the return Organization + * + * @return string + * @access public + */ + function getOrganization(){ + return $this->data[9]; + } + + /** + * Get the return Error + * + * @return string + * @access public + */ + function getError(){ + return $this->data[10]; + + } + + /** + * Formats the url to submit to Maxmind and returns data in an array + * + * @access private + */ + function _process(){ + $url = "http://maxmind.com:8010/f?l=" . $this->licenceKey . "&i=" . $this->ip; + $response = $this->_queryMaxMind($url); + $this->data = $this->csv_split( trim($response) ); + } + + + } + ?> \ No newline at end of file diff --git a/modules/maxmind_geoip/includes/maxmind-ws/MaxMindWebServices.class.php b/modules/maxmind_geoip/includes/maxmind-ws/MaxMindWebServices.class.php index 4f8ced72c..048a449e0 100755 --- a/modules/maxmind_geoip/includes/maxmind-ws/MaxMindWebServices.class.php +++ b/modules/maxmind_geoip/includes/maxmind-ws/MaxMindWebServices.class.php @@ -1,176 +1,176 @@ - - * - */ - -class MaxMindWebServices { - - - /** - * The licence Key for of a Maxmind web services account - * - * @var string - * @access private - */ - var $licenceKey = ""; - - - /** - * An array that holds all returned values from a Maxmind request - * - * @var array - * @access private - */ - var $data = array(); - - /** - * Set the Licence Key - * - * @var string - * @access public - */ - function setLicenceKey($key){ - $this->licenceKey = $key; - } - - /** - * Test to see if the Service produced an Error - * - * @return bool - * @access public - */ - function isError(){ - $error = $this->getError(); - if( isset($error) ) return true; - else return false; - } - - /** - * Get all Results in a single array for fast processing - * - * @return array - * @access public - */ - function getResultArray(){ - return $this->data; - } - - /** - * Returns the City and State from a metro code - * - * @param string - * @return string - * @access public - */ - function lookupMetroCode($code){ - if( !isset($this->_metroCodes) ){ - $this->_metroCodes = parse_ini_file(dirname( __FILE__ ).'/ini/metroCodes.ini'); - } - return $this->_metroCodes[$code]; - } - - /** - * Returns the Country Name from the code - * - * @param string - * @return string - * @access public - */ - function lookupCountryCode($code){ - if( !isset($this->_countryCodes) ){ - $this->_countryCodes = parse_ini_file(dirname( __FILE__ ).'/ini/countryCodes.ini'); - } - return $this->_countryCodes["'".$code."'"]; - } - - /** - * Returns the SubCountry Name from the code ( States, Provinces ) - * - * @param string - * @param string - * @return string - * @access public - */ - function lookupSubCountryCode($code, $countryCode){ - if( !isset($this->_subCountryCodes) ){ - $this->_subCountryCodes = parse_ini_file(dirname( __FILE__ ).'/ini/subCountryCodes.ini', true); - } - if( is_array($this->_subCountryCodes["'".$countryCode."'"]) ){ - return $this->_subCountryCodes["'".$countryCode."'"]["'".$code."'"]; - } - } - /** - * Generic Web Service Request for MaxMind - * - * @access private - */ - function _queryMaxMind($url){ - - $ch = curl_init(); // initialize curl handle - curl_setopt($ch, CURLOPT_URL,$url); // set url to post to - curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_TIMEOUT, 4); // times out after 4s - - return curl_exec($ch); - - } - - - /** - * Function to handle parsing the csv string returned from MaxMind - * - * This function was found in the comments section on: - * http://www.php.net/manual/en/function.fgetcsv.php - * - * @var string csv line to parse - * @var string delimiter to use for spliting - * @var bool remove quotes around values - * @return array the parts of the csv line - * @access public - * @author php@dogpoop.cjb.net - */ - - function csv_split($line,$delim=',',$removeQuotes=true) { - - $fields = array(); - $fldCount = 0; - $inQuotes = false; - for ($i = 0; $i < strlen($line); $i++) { - if (!isset($fields[$fldCount])) $fields[$fldCount] = ""; - $tmp = substr($line,$i,strlen($delim)); - - if ($tmp === $delim && !$inQuotes) { - $fldCount++; - $i += strlen($delim)-1; - } - else if ($fields[$fldCount] == "" && $line[$i] == '"' && !$inQuotes) { - if (!$removeQuotes) $fields[$fldCount] .= $line[$i]; - $inQuotes = true; - } - else if ($line[$i] == '"') { - if ($line[$i+1] == '"') { - $i++; - $fields[$fldCount] .= $line[$i]; - } - else { - if (!$removeQuotes) $fields[$fldCount] .= $line[$i]; - $inQuotes = false; - } - } - else { - $fields[$fldCount] .= $line[$i]; - } - } - return $fields; - } - - -} - -?> + + * + */ + +class MaxMindWebServices { + + + /** + * The licence Key for of a Maxmind web services account + * + * @var string + * @access private + */ + var $licenceKey = ""; + + + /** + * An array that holds all returned values from a Maxmind request + * + * @var array + * @access private + */ + var $data = array(); + + /** + * Set the Licence Key + * + * @var string + * @access public + */ + function setLicenceKey($key){ + $this->licenceKey = $key; + } + + /** + * Test to see if the Service produced an Error + * + * @return bool + * @access public + */ + function isError(){ + $error = $this->getError(); + if( isset($error) ) return true; + else return false; + } + + /** + * Get all Results in a single array for fast processing + * + * @return array + * @access public + */ + function getResultArray(){ + return $this->data; + } + + /** + * Returns the City and State from a metro code + * + * @param string + * @return string + * @access public + */ + function lookupMetroCode($code){ + if( !isset($this->_metroCodes) ){ + $this->_metroCodes = parse_ini_file(dirname( __FILE__ ).'/ini/metroCodes.ini'); + } + return $this->_metroCodes[$code]; + } + + /** + * Returns the Country Name from the code + * + * @param string + * @return string + * @access public + */ + function lookupCountryCode($code){ + if( !isset($this->_countryCodes) ){ + $this->_countryCodes = parse_ini_file(dirname( __FILE__ ).'/ini/countryCodes.ini'); + } + return $this->_countryCodes["'".$code."'"]; + } + + /** + * Returns the SubCountry Name from the code ( States, Provinces ) + * + * @param string + * @param string + * @return string + * @access public + */ + function lookupSubCountryCode($code, $countryCode){ + if( !isset($this->_subCountryCodes) ){ + $this->_subCountryCodes = parse_ini_file(dirname( __FILE__ ).'/ini/subCountryCodes.ini', true); + } + if( is_array($this->_subCountryCodes["'".$countryCode."'"]) ){ + return $this->_subCountryCodes["'".$countryCode."'"]["'".$code."'"]; + } + } + /** + * Generic Web Service Request for MaxMind + * + * @access private + */ + function _queryMaxMind($url){ + + $ch = curl_init(); // initialize curl handle + curl_setopt($ch, CURLOPT_URL,$url); // set url to post to + curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_TIMEOUT, 4); // times out after 4s + + return curl_exec($ch); + + } + + + /** + * Function to handle parsing the csv string returned from MaxMind + * + * This function was found in the comments section on: + * http://www.php.net/manual/en/function.fgetcsv.php + * + * @var string csv line to parse + * @var string delimiter to use for spliting + * @var bool remove quotes around values + * @return array the parts of the csv line + * @access public + * @author php@dogpoop.cjb.net + */ + + function csv_split($line,$delim=',',$removeQuotes=true) { + + $fields = array(); + $fldCount = 0; + $inQuotes = false; + for ($i = 0; $i < strlen($line); $i++) { + if (!isset($fields[$fldCount])) $fields[$fldCount] = ""; + $tmp = substr($line,$i,strlen($delim)); + + if ($tmp === $delim && !$inQuotes) { + $fldCount++; + $i += strlen($delim)-1; + } + else if ($fields[$fldCount] == "" && $line[$i] == '"' && !$inQuotes) { + if (!$removeQuotes) $fields[$fldCount] .= $line[$i]; + $inQuotes = true; + } + else if ($line[$i] == '"') { + if ($line[$i+1] == '"') { + $i++; + $fields[$fldCount] .= $line[$i]; + } + else { + if (!$removeQuotes) $fields[$fldCount] .= $line[$i]; + $inQuotes = false; + } + } + else { + $fields[$fldCount] .= $line[$i]; + } + } + return $fields; + } + + +} + +?> diff --git a/modules/maxmind_geoip/includes/maxmind-ws/ini/countryCodes.ini b/modules/maxmind_geoip/includes/maxmind-ws/ini/countryCodes.ini index b155b2fc4..44890e263 100755 --- a/modules/maxmind_geoip/includes/maxmind-ws/ini/countryCodes.ini +++ b/modules/maxmind_geoip/includes/maxmind-ws/ini/countryCodes.ini @@ -1,245 +1,245 @@ -'A1' = "Anonymous Proxy" -'A2' = "Satellite Provider" -'AD' = "Andorra" -'AE' = "United Arab Emirates" -'AF' = "Afghanistan" -'AG' = "Antigua and Barbuda" -'AI' = "Anguilla" -'AL' = "Albania" -'AM' = "Armenia" -'AN' = "Netherlands Antilles" -'AO' = "Angola" -'AP' = "Asia/Pacific Region" -'AQ' = "Antarctica" -'AR' = "Argentina" -'AS' = "American Samoa" -'AT' = "Austria" -'AU' = "Australia" -'AW' = "Aruba" -'AZ' = "Azerbaijan" -'BA' = "Bosnia and Herzegovina" -'BB' = "Barbados" -'BD' = "Bangladesh" -'BE' = "Belgium" -'BF' = "Burkina Faso" -'BG' = "Bulgaria" -'BH' = "Bahrain" -'BI' = "Burundi" -'BJ' = "Benin" -'BM' = "Bermuda" -'BN' = "Brunei Darussalam" -'BO' = "Bolivia" -'BR' = "Brazil" -'BS' = "Bahamas" -'BT' = "Bhutan" -'BV' = "Bouvet Island" -'BW' = "Botswana" -'BY' = "Belarus" -'BZ' = "Belize" -'CA' = "Canada" -'CC' = "Cocos (Keeling) Islands" -'CD' = "Congo, The Democratic Republic of the" -'CF' = "Central African Republic" -'CG' = "Congo" -'CH' = "Switzerland" -'CI' = "Cote D'Ivoire" -'CK' = "Cook Islands" -'CL' = "Chile" -'CM' = "Cameroon" -'CN' = "China" -'CO' = "Colombia" -'CR' = "Costa Rica" -'CS' = "Serbia and Montenegro" -'CU' = "Cuba" -'CV' = "Cape Verde" -'CX' = "Christmas Island" -'CY' = "Cyprus" -'CZ' = "Czech Republic" -'DE' = "Germany" -'DJ' = "Djibouti" -'DK' = "Denmark" -'DM' = "Dominica" -'DO' = "Dominican Republic" -'DZ' = "Algeria" -'EC' = "Ecuador" -'EE' = "Estonia" -'EG' = "Egypt" -'EH' = "Western Sahara" -'ER' = "Eritrea" -'ES' = "Spain" -'ET' = "Ethiopia" -'EU' = "Europe" -'FI' = "Finland" -'FJ' = "Fiji" -'FK' = "Falkland Islands (Malvinas)" -'FM' = "Micronesia, Federated States of" -'FO' = "Faroe Islands" -'FR' = "France" -'FX' = "France, Metropolitan" -'GA' = "Gabon" -'GB' = "United Kingdom" -'GD' = "Grenada" -'GE' = "Georgia" -'GF' = "French Guiana" -'GH' = "Ghana" -'GI' = "Gibraltar" -'GL' = "Greenland" -'GM' = "Gambia" -'GN' = "Guinea" -'GP' = "Guadeloupe" -'GQ' = "Equatorial Guinea" -'GR' = "Greece" -'GS' = "South Georgia and the South Sandwich Islands" -'GT' = "Guatemala" -'GU' = "Guam" -'GW' = "Guinea-Bissau" -'GY' = "Guyana" -'HK' = "Hong Kong" -'HM' = "Heard Island and McDonald Islands" -'HN' = "Honduras" -'HR' = "Croatia" -'HT' = "Haiti" -'HU' = "Hungary" -'ID' = "Indonesia" -'IE' = "Ireland" -'IL' = "Israel" -'IN' = "India" -'IO' = "British Indian Ocean Territory" -'IQ' = "Iraq" -'IR' = "Iran, Islamic Republic of" -'IS' = "Iceland" -'IT' = "Italy" -'JM' = "Jamaica" -'JO' = "Jordan" -'JP' = "Japan" -'KE' = "Kenya" -'KG' = "Kyrgyzstan" -'KH' = "Cambodia" -'KI' = "Kiribati" -'KM' = "Comoros" -'KN' = "Saint Kitts and Nevis" -'KP' = "Korea, Democratic People's Republic of" -'KR' = "Korea, Republic of" -'KW' = "Kuwait" -'KY' = "Cayman Islands" -'KZ' = "Kazakhstan" -'LA' = "Lao People's Democratic Republic" -'LB' = "Lebanon" -'LC' = "Saint Lucia" -'LI' = "Liechtenstein" -'LK' = "Sri Lanka" -'LR' = "Liberia" -'LS' = "Lesotho" -'LT' = "Lithuania" -'LU' = "Luxembourg" -'LV' = "Latvia" -'LY' = "Libyan Arab Jamahiriya" -'MA' = "Morocco" -'MC' = "Monaco" -'MD' = "Moldova, Republic of" -'MG' = "Madagascar" -'MH' = "Marshall Islands" -'MK' = "Macedonia" -'ML' = "Mali" -'MM' = "Myanmar" -'MN' = "Mongolia" -'MO' = "Macau" -'MP' = "Northern Mariana Islands" -'MQ' = "Martinique" -'MR' = "Mauritania" -'MS' = "Montserrat" -'MT' = "Malta" -'MU' = "Mauritius" -'MV' = "Maldives" -'MW' = "Malawi" -'MX' = "Mexico" -'MY' = "Malaysia" -'MZ' = "Mozambique" -'NA' = "Namibia" -'NC' = "New Caledonia" -'NE' = "Niger" -'NF' = "Norfolk Island" -'NG' = "Nigeria" -'NI' = "Nicaragua" -'NL' = "Netherlands" -'NO' = "Norway" -'NP' = "Nepal" -'NR' = "Nauru" -'NU' = "Niue" -'NZ' = "New Zealand" -'OM' = "Oman" -'PA' = "Panama" -'PE' = "Peru" -'PF' = "French Polynesia" -'PG' = "Papua New Guinea" -'PH' = "Philippines" -'PK' = "Pakistan" -'PL' = "Poland" -'PM' = "Saint Pierre and Miquelon" -'PN' = "Pitcairn" -'PR' = "Puerto Rico" -'PS' = "Palestinian Territory" -'PT' = "Portugal" -'PW' = "Palau" -'PY' = "Paraguay" -'QA' = "Qatar" -'RE' = "Reunion" -'RO' = "Romania" -'RU' = "Russian Federation" -'RW' = "Rwanda" -'SA' = "Saudi Arabia" -'SB' = "Solomon Islands" -'SC' = "Seychelles" -'SD' = "Sudan" -'SE' = "Sweden" -'SG' = "Singapore" -'SH' = "Saint Helena" -'SI' = "Slovenia" -'SJ' = "Svalbard and Jan Mayen" -'SK' = "Slovakia" -'SL' = "Sierra Leone" -'SM' = "San Marino" -'SN' = "Senegal" -'SO' = "Somalia" -'SR' = "Suriname" -'ST' = "Sao Tome and Principe" -'SV' = "El Salvador" -'SY' = "Syrian Arab Republic" -'SZ' = "Swaziland" -'TC' = "Turks and Caicos Islands" -'TD' = "Chad" -'TF' = "French Southern Territories" -'TG' = "Togo" -'TH' = "Thailand" -'TJ' = "Tajikistan" -'TK' = "Tokelau" -'TL' = "East Timor" -'TM' = "Turkmenistan" -'TN' = "Tunisia" -'TO' = "Tonga" -'TR' = "Turkey" -'TT' = "Trinidad and Tobago" -'TV' = "Tuvalu" -'TW' = "Taiwan" -'TZ' = "Tanzania, United Republic of" -'UA' = "Ukraine" -'UG' = "Uganda" -'UM' = "United States Minor Outlying Islands" -'US' = "United States" -'UY' = "Uruguay" -'UZ' = "Uzbekistan" -'VA' = "Holy See (Vatican City State)" -'VC' = "Saint Vincent and the Grenadines" -'VE' = "Venezuela" -'VG' = "Virgin Islands, British" -'VI' = "Virgin Islands, U.S." -'VN' = "Vietnam" -'VU' = "Vanuatu" -'WF' = "Wallis and Futuna" -'WS' = "Samoa" -'YE' = "Yemen" -'YT' = "Mayotte" -'ZA' = "South Africa" -'ZM' = "Zambia" -'ZR' = "Zaire" +'A1' = "Anonymous Proxy" +'A2' = "Satellite Provider" +'AD' = "Andorra" +'AE' = "United Arab Emirates" +'AF' = "Afghanistan" +'AG' = "Antigua and Barbuda" +'AI' = "Anguilla" +'AL' = "Albania" +'AM' = "Armenia" +'AN' = "Netherlands Antilles" +'AO' = "Angola" +'AP' = "Asia/Pacific Region" +'AQ' = "Antarctica" +'AR' = "Argentina" +'AS' = "American Samoa" +'AT' = "Austria" +'AU' = "Australia" +'AW' = "Aruba" +'AZ' = "Azerbaijan" +'BA' = "Bosnia and Herzegovina" +'BB' = "Barbados" +'BD' = "Bangladesh" +'BE' = "Belgium" +'BF' = "Burkina Faso" +'BG' = "Bulgaria" +'BH' = "Bahrain" +'BI' = "Burundi" +'BJ' = "Benin" +'BM' = "Bermuda" +'BN' = "Brunei Darussalam" +'BO' = "Bolivia" +'BR' = "Brazil" +'BS' = "Bahamas" +'BT' = "Bhutan" +'BV' = "Bouvet Island" +'BW' = "Botswana" +'BY' = "Belarus" +'BZ' = "Belize" +'CA' = "Canada" +'CC' = "Cocos (Keeling) Islands" +'CD' = "Congo, The Democratic Republic of the" +'CF' = "Central African Republic" +'CG' = "Congo" +'CH' = "Switzerland" +'CI' = "Cote D'Ivoire" +'CK' = "Cook Islands" +'CL' = "Chile" +'CM' = "Cameroon" +'CN' = "China" +'CO' = "Colombia" +'CR' = "Costa Rica" +'CS' = "Serbia and Montenegro" +'CU' = "Cuba" +'CV' = "Cape Verde" +'CX' = "Christmas Island" +'CY' = "Cyprus" +'CZ' = "Czech Republic" +'DE' = "Germany" +'DJ' = "Djibouti" +'DK' = "Denmark" +'DM' = "Dominica" +'DO' = "Dominican Republic" +'DZ' = "Algeria" +'EC' = "Ecuador" +'EE' = "Estonia" +'EG' = "Egypt" +'EH' = "Western Sahara" +'ER' = "Eritrea" +'ES' = "Spain" +'ET' = "Ethiopia" +'EU' = "Europe" +'FI' = "Finland" +'FJ' = "Fiji" +'FK' = "Falkland Islands (Malvinas)" +'FM' = "Micronesia, Federated States of" +'FO' = "Faroe Islands" +'FR' = "France" +'FX' = "France, Metropolitan" +'GA' = "Gabon" +'GB' = "United Kingdom" +'GD' = "Grenada" +'GE' = "Georgia" +'GF' = "French Guiana" +'GH' = "Ghana" +'GI' = "Gibraltar" +'GL' = "Greenland" +'GM' = "Gambia" +'GN' = "Guinea" +'GP' = "Guadeloupe" +'GQ' = "Equatorial Guinea" +'GR' = "Greece" +'GS' = "South Georgia and the South Sandwich Islands" +'GT' = "Guatemala" +'GU' = "Guam" +'GW' = "Guinea-Bissau" +'GY' = "Guyana" +'HK' = "Hong Kong" +'HM' = "Heard Island and McDonald Islands" +'HN' = "Honduras" +'HR' = "Croatia" +'HT' = "Haiti" +'HU' = "Hungary" +'ID' = "Indonesia" +'IE' = "Ireland" +'IL' = "Israel" +'IN' = "India" +'IO' = "British Indian Ocean Territory" +'IQ' = "Iraq" +'IR' = "Iran, Islamic Republic of" +'IS' = "Iceland" +'IT' = "Italy" +'JM' = "Jamaica" +'JO' = "Jordan" +'JP' = "Japan" +'KE' = "Kenya" +'KG' = "Kyrgyzstan" +'KH' = "Cambodia" +'KI' = "Kiribati" +'KM' = "Comoros" +'KN' = "Saint Kitts and Nevis" +'KP' = "Korea, Democratic People's Republic of" +'KR' = "Korea, Republic of" +'KW' = "Kuwait" +'KY' = "Cayman Islands" +'KZ' = "Kazakhstan" +'LA' = "Lao People's Democratic Republic" +'LB' = "Lebanon" +'LC' = "Saint Lucia" +'LI' = "Liechtenstein" +'LK' = "Sri Lanka" +'LR' = "Liberia" +'LS' = "Lesotho" +'LT' = "Lithuania" +'LU' = "Luxembourg" +'LV' = "Latvia" +'LY' = "Libyan Arab Jamahiriya" +'MA' = "Morocco" +'MC' = "Monaco" +'MD' = "Moldova, Republic of" +'MG' = "Madagascar" +'MH' = "Marshall Islands" +'MK' = "Macedonia" +'ML' = "Mali" +'MM' = "Myanmar" +'MN' = "Mongolia" +'MO' = "Macau" +'MP' = "Northern Mariana Islands" +'MQ' = "Martinique" +'MR' = "Mauritania" +'MS' = "Montserrat" +'MT' = "Malta" +'MU' = "Mauritius" +'MV' = "Maldives" +'MW' = "Malawi" +'MX' = "Mexico" +'MY' = "Malaysia" +'MZ' = "Mozambique" +'NA' = "Namibia" +'NC' = "New Caledonia" +'NE' = "Niger" +'NF' = "Norfolk Island" +'NG' = "Nigeria" +'NI' = "Nicaragua" +'NL' = "Netherlands" +'NO' = "Norway" +'NP' = "Nepal" +'NR' = "Nauru" +'NU' = "Niue" +'NZ' = "New Zealand" +'OM' = "Oman" +'PA' = "Panama" +'PE' = "Peru" +'PF' = "French Polynesia" +'PG' = "Papua New Guinea" +'PH' = "Philippines" +'PK' = "Pakistan" +'PL' = "Poland" +'PM' = "Saint Pierre and Miquelon" +'PN' = "Pitcairn" +'PR' = "Puerto Rico" +'PS' = "Palestinian Territory" +'PT' = "Portugal" +'PW' = "Palau" +'PY' = "Paraguay" +'QA' = "Qatar" +'RE' = "Reunion" +'RO' = "Romania" +'RU' = "Russian Federation" +'RW' = "Rwanda" +'SA' = "Saudi Arabia" +'SB' = "Solomon Islands" +'SC' = "Seychelles" +'SD' = "Sudan" +'SE' = "Sweden" +'SG' = "Singapore" +'SH' = "Saint Helena" +'SI' = "Slovenia" +'SJ' = "Svalbard and Jan Mayen" +'SK' = "Slovakia" +'SL' = "Sierra Leone" +'SM' = "San Marino" +'SN' = "Senegal" +'SO' = "Somalia" +'SR' = "Suriname" +'ST' = "Sao Tome and Principe" +'SV' = "El Salvador" +'SY' = "Syrian Arab Republic" +'SZ' = "Swaziland" +'TC' = "Turks and Caicos Islands" +'TD' = "Chad" +'TF' = "French Southern Territories" +'TG' = "Togo" +'TH' = "Thailand" +'TJ' = "Tajikistan" +'TK' = "Tokelau" +'TL' = "East Timor" +'TM' = "Turkmenistan" +'TN' = "Tunisia" +'TO' = "Tonga" +'TR' = "Turkey" +'TT' = "Trinidad and Tobago" +'TV' = "Tuvalu" +'TW' = "Taiwan" +'TZ' = "Tanzania, United Republic of" +'UA' = "Ukraine" +'UG' = "Uganda" +'UM' = "United States Minor Outlying Islands" +'US' = "United States" +'UY' = "Uruguay" +'UZ' = "Uzbekistan" +'VA' = "Holy See (Vatican City State)" +'VC' = "Saint Vincent and the Grenadines" +'VE' = "Venezuela" +'VG' = "Virgin Islands, British" +'VI' = "Virgin Islands, U.S." +'VN' = "Vietnam" +'VU' = "Vanuatu" +'WF' = "Wallis and Futuna" +'WS' = "Samoa" +'YE' = "Yemen" +'YT' = "Mayotte" +'ZA' = "South Africa" +'ZM' = "Zambia" +'ZR' = "Zaire" 'ZW' = "Zimbabwe" \ No newline at end of file diff --git a/modules/maxmind_geoip/includes/maxmind-ws/ini/metroCodes.ini b/modules/maxmind_geoip/includes/maxmind-ws/ini/metroCodes.ini index 4cb08250f..15e853339 100755 --- a/modules/maxmind_geoip/includes/maxmind-ws/ini/metroCodes.ini +++ b/modules/maxmind_geoip/includes/maxmind-ws/ini/metroCodes.ini @@ -1,212 +1,212 @@ -500 = Portland-Auburn, ME -501 = New York, NY -502 = Binghamton, NY -503 = Macon, GA -504 = Philadelphia, PA -505 = Detroit, MI -506 = Boston, MA -507 = Savannah, GA -508 = Pittsburgh, PA -509 = Ft Wayne, IN -510 = Cleveland, OH -511 = Washington, DC -512 = Baltimore, MD -513 = Flint, MI -514 = Buffalo, NY -515 = Cincinnati, OH -516 = Erie, PA -517 = Charlotte, NC -518 = Greensboro, NC -519 = Charleston, SC -520 = Augusta, GA -521 = Providence, RI -522 = Columbus, GA -523 = Burlington, VT -524 = Atlanta, GA -525 = Albany, GA -526 = Utica-Rome, NY -527 = Indianapolis, IN -528 = Miami, FL -529 = Louisville, KY -530 = Tallahassee, FL -531 = Tri-Cities, TN -532 = Albany-Schenectady-Troy, NY -533 = Hartford, CT -534 = Orlando, FL -535 = Columbus, OH -536 = Youngstown-Warren, OH -537 = Bangor, ME -538 = Rochester, NY -539 = Tampa, FL -540 = Traverse City-Cadillac, MI -541 = Lexington, KY -542 = Dayton, OH -543 = Springfield-Holyoke, MA -544 = Norfolk-Portsmouth, VA -545 = Greenville-New Bern-Washington, NC -546 = Columbia, SC -547 = Toledo, OH -548 = West Palm Beach, FL -549 = Watertown, NY -550 = Wilmington, NC -551 = Lansing, MI -552 = Presque Isle, ME -553 = Marquette, MI -554 = Wheeling, WV -555 = Syracuse, NY -556 = Richmond-Petersburg, VA -557 = Knoxville, TN -558 = Lima, OH -559 = Bluefield-Beckley-Oak Hill, WV -560 = Raleigh-Durham, NC -561 = Jacksonville, FL -563 = Grand Rapids, MI -564 = Charleston-Huntington, WV -565 = Elmira, NY -566 = Harrisburg-Lancaster-Lebanon-York, PA -567 = Greenville-Spartenburg, SC -569 = Harrisonburg, VA -570 = Florence-Myrtle Beach, SC -571 = Ft Myers, FL -573 = Roanoke-Lynchburg, VA -574 = Johnstown-Altoona, PA -575 = Chattanooga, TN -576 = Salisbury, MD -577 = Wilkes Barre-Scranton, PA -581 = Terre Haute, IN -582 = Lafayette, IN -583 = Alpena, MI -584 = Charlottesville, VA -588 = South Bend, IN -592 = Gainesville, FL -596 = Zanesville, OH -597 = Parkersburg, WV -598 = Clarksburg-Weston, WV -600 = Corpus Christi, TX -602 = Chicago, IL -603 = Joplin-Pittsburg, MO -604 = Columbia-Jefferson City, MO -605 = Topeka, KS -606 = Dothan, AL -609 = St Louis, MO -610 = Rockford, IL -611 = Rochester-Mason City-Austin, MN -612 = Shreveport, LA -613 = Minneapolis-St Paul, MN -616 = Kansas City, MO -617 = Milwaukee, WI -618 = Houston, TX -619 = Springfield, MO -620 = Tuscaloosa, AL -622 = New Orleans, LA -623 = Dallas-Fort Worth, TX -624 = Sioux City, IA -625 = Waco-Temple-Bryan, TX -626 = Victoria, TX -627 = Wichita Falls, TX -628 = Monroe, LA -630 = Birmingham, AL -631 = Ottumwa-Kirksville, IA -632 = Paducah, KY -633 = Odessa-Midland, TX -634 = Amarillo, TX -635 = Austin, TX -636 = Harlingen, TX -637 = Cedar Rapids-Waterloo, IA -638 = St Joseph, MO -639 = Jackson, TN -640 = Memphis, TN -641 = San Antonio, TX -642 = Lafayette, LA -643 = Lake Charles, LA -644 = Alexandria, LA -646 = Anniston, AL -647 = Greenwood-Greenville, MS -648 = Champaign-Springfield-Decatur, IL -649 = Evansville, IN -650 = Oklahoma City, OK -651 = Lubbock, TX -652 = Omaha, NE -656 = Panama City, FL -657 = Sherman, TX -658 = Green Bay-Appleton, WI -659 = Nashville, TN -661 = San Angelo, TX -662 = Abilene-Sweetwater, TX -669 = Madison, WI -670 = Ft Smith-Fay-Springfield, AR -671 = Tulsa, OK -673 = Columbus-Tupelo-West Point, MS -675 = Peoria-Bloomington, IL -676 = Duluth, MN -678 = Wichita, KS -679 = Des Moines, IA -682 = Davenport-Rock Island-Moline, IL -686 = Mobile, AL -687 = Minot-Bismarck-Dickinson, ND -691 = Huntsville, AL -692 = Beaumont-Port Author, TX -693 = Little Rock-Pine Bluff, AR -698 = Montgomery, AL -702 = La Crosse-Eau Claire, WI -705 = Wausau-Rhinelander, WI -709 = Tyler-Longview, TX -710 = Hattiesburg-Laurel, MS -711 = Meridian, MS -716 = Baton Rouge, LA -717 = Quincy, IL -718 = Jackson, MS -722 = Lincoln-Hastings, NE -724 = Fargo-Valley City, ND -725 = Sioux Falls, SD -734 = Jonesboro, AR -736 = Bowling Green, KY -737 = Mankato, MN -740 = North Platte, NE -743 = Anchorage, AK -744 = Honolulu, HI -745 = Fairbanks, AK -746 = Biloxi-Gulfport, MS -747 = Juneau, AK -749 = Laredo, TX -751 = Denver, CO -752 = Colorado Springs, CO -753 = Phoenix, AZ -754 = Butte-Bozeman, MT -755 = Great Falls, MT -756 = Billings, MT -757 = Boise, ID -758 = Idaho Falls-Pocatello, ID -759 = Cheyenne, WY -760 = Twin Falls, ID -762 = Missoula, MT -764 = Rapid City, SD -765 = El Paso, TX -766 = Helena, MT -767 = Casper-Riverton, WY -770 = Salt Lake City, UT -771 = Yuma, AZ -773 = Grand Junction, CO -789 = Tucson, AZ -790 = Albuquerque, NM -798 = Glendive, MT -800 = Bakersfield, CA -801 = Eugene, OR -802 = Eureka, CA -803 = Los Angeles, CA -804 = Palm Springs, CA -807 = San Francisco, CA -810 = Yakima-Pasco, WA -811 = Reno, NV -813 = Medford-Klamath Falls, OR -819 = Seattle-Tacoma, WA -820 = Portland, OR -821 = Bend, OR -825 = San Diego, CA -828 = Monterey-Salinas, CA -839 = Las Vegas, NV -855 = Santa Barbara, CA -862 = Sacramento, CA -866 = Fresno, CA -868 = Chico-Redding, CA +500 = Portland-Auburn, ME +501 = New York, NY +502 = Binghamton, NY +503 = Macon, GA +504 = Philadelphia, PA +505 = Detroit, MI +506 = Boston, MA +507 = Savannah, GA +508 = Pittsburgh, PA +509 = Ft Wayne, IN +510 = Cleveland, OH +511 = Washington, DC +512 = Baltimore, MD +513 = Flint, MI +514 = Buffalo, NY +515 = Cincinnati, OH +516 = Erie, PA +517 = Charlotte, NC +518 = Greensboro, NC +519 = Charleston, SC +520 = Augusta, GA +521 = Providence, RI +522 = Columbus, GA +523 = Burlington, VT +524 = Atlanta, GA +525 = Albany, GA +526 = Utica-Rome, NY +527 = Indianapolis, IN +528 = Miami, FL +529 = Louisville, KY +530 = Tallahassee, FL +531 = Tri-Cities, TN +532 = Albany-Schenectady-Troy, NY +533 = Hartford, CT +534 = Orlando, FL +535 = Columbus, OH +536 = Youngstown-Warren, OH +537 = Bangor, ME +538 = Rochester, NY +539 = Tampa, FL +540 = Traverse City-Cadillac, MI +541 = Lexington, KY +542 = Dayton, OH +543 = Springfield-Holyoke, MA +544 = Norfolk-Portsmouth, VA +545 = Greenville-New Bern-Washington, NC +546 = Columbia, SC +547 = Toledo, OH +548 = West Palm Beach, FL +549 = Watertown, NY +550 = Wilmington, NC +551 = Lansing, MI +552 = Presque Isle, ME +553 = Marquette, MI +554 = Wheeling, WV +555 = Syracuse, NY +556 = Richmond-Petersburg, VA +557 = Knoxville, TN +558 = Lima, OH +559 = Bluefield-Beckley-Oak Hill, WV +560 = Raleigh-Durham, NC +561 = Jacksonville, FL +563 = Grand Rapids, MI +564 = Charleston-Huntington, WV +565 = Elmira, NY +566 = Harrisburg-Lancaster-Lebanon-York, PA +567 = Greenville-Spartenburg, SC +569 = Harrisonburg, VA +570 = Florence-Myrtle Beach, SC +571 = Ft Myers, FL +573 = Roanoke-Lynchburg, VA +574 = Johnstown-Altoona, PA +575 = Chattanooga, TN +576 = Salisbury, MD +577 = Wilkes Barre-Scranton, PA +581 = Terre Haute, IN +582 = Lafayette, IN +583 = Alpena, MI +584 = Charlottesville, VA +588 = South Bend, IN +592 = Gainesville, FL +596 = Zanesville, OH +597 = Parkersburg, WV +598 = Clarksburg-Weston, WV +600 = Corpus Christi, TX +602 = Chicago, IL +603 = Joplin-Pittsburg, MO +604 = Columbia-Jefferson City, MO +605 = Topeka, KS +606 = Dothan, AL +609 = St Louis, MO +610 = Rockford, IL +611 = Rochester-Mason City-Austin, MN +612 = Shreveport, LA +613 = Minneapolis-St Paul, MN +616 = Kansas City, MO +617 = Milwaukee, WI +618 = Houston, TX +619 = Springfield, MO +620 = Tuscaloosa, AL +622 = New Orleans, LA +623 = Dallas-Fort Worth, TX +624 = Sioux City, IA +625 = Waco-Temple-Bryan, TX +626 = Victoria, TX +627 = Wichita Falls, TX +628 = Monroe, LA +630 = Birmingham, AL +631 = Ottumwa-Kirksville, IA +632 = Paducah, KY +633 = Odessa-Midland, TX +634 = Amarillo, TX +635 = Austin, TX +636 = Harlingen, TX +637 = Cedar Rapids-Waterloo, IA +638 = St Joseph, MO +639 = Jackson, TN +640 = Memphis, TN +641 = San Antonio, TX +642 = Lafayette, LA +643 = Lake Charles, LA +644 = Alexandria, LA +646 = Anniston, AL +647 = Greenwood-Greenville, MS +648 = Champaign-Springfield-Decatur, IL +649 = Evansville, IN +650 = Oklahoma City, OK +651 = Lubbock, TX +652 = Omaha, NE +656 = Panama City, FL +657 = Sherman, TX +658 = Green Bay-Appleton, WI +659 = Nashville, TN +661 = San Angelo, TX +662 = Abilene-Sweetwater, TX +669 = Madison, WI +670 = Ft Smith-Fay-Springfield, AR +671 = Tulsa, OK +673 = Columbus-Tupelo-West Point, MS +675 = Peoria-Bloomington, IL +676 = Duluth, MN +678 = Wichita, KS +679 = Des Moines, IA +682 = Davenport-Rock Island-Moline, IL +686 = Mobile, AL +687 = Minot-Bismarck-Dickinson, ND +691 = Huntsville, AL +692 = Beaumont-Port Author, TX +693 = Little Rock-Pine Bluff, AR +698 = Montgomery, AL +702 = La Crosse-Eau Claire, WI +705 = Wausau-Rhinelander, WI +709 = Tyler-Longview, TX +710 = Hattiesburg-Laurel, MS +711 = Meridian, MS +716 = Baton Rouge, LA +717 = Quincy, IL +718 = Jackson, MS +722 = Lincoln-Hastings, NE +724 = Fargo-Valley City, ND +725 = Sioux Falls, SD +734 = Jonesboro, AR +736 = Bowling Green, KY +737 = Mankato, MN +740 = North Platte, NE +743 = Anchorage, AK +744 = Honolulu, HI +745 = Fairbanks, AK +746 = Biloxi-Gulfport, MS +747 = Juneau, AK +749 = Laredo, TX +751 = Denver, CO +752 = Colorado Springs, CO +753 = Phoenix, AZ +754 = Butte-Bozeman, MT +755 = Great Falls, MT +756 = Billings, MT +757 = Boise, ID +758 = Idaho Falls-Pocatello, ID +759 = Cheyenne, WY +760 = Twin Falls, ID +762 = Missoula, MT +764 = Rapid City, SD +765 = El Paso, TX +766 = Helena, MT +767 = Casper-Riverton, WY +770 = Salt Lake City, UT +771 = Yuma, AZ +773 = Grand Junction, CO +789 = Tucson, AZ +790 = Albuquerque, NM +798 = Glendive, MT +800 = Bakersfield, CA +801 = Eugene, OR +802 = Eureka, CA +803 = Los Angeles, CA +804 = Palm Springs, CA +807 = San Francisco, CA +810 = Yakima-Pasco, WA +811 = Reno, NV +813 = Medford-Klamath Falls, OR +819 = Seattle-Tacoma, WA +820 = Portland, OR +821 = Bend, OR +825 = San Diego, CA +828 = Monterey-Salinas, CA +839 = Las Vegas, NV +855 = Santa Barbara, CA +862 = Sacramento, CA +866 = Fresno, CA +868 = Chico-Redding, CA 881 = Spokane, WA \ No newline at end of file diff --git a/modules/maxmind_geoip/includes/maxmind-ws/ini/subCountryCodes.ini b/modules/maxmind_geoip/includes/maxmind-ws/ini/subCountryCodes.ini index 1090e3b50..64107e545 100755 --- a/modules/maxmind_geoip/includes/maxmind-ws/ini/subCountryCodes.ini +++ b/modules/maxmind_geoip/includes/maxmind-ws/ini/subCountryCodes.ini @@ -1,77 +1,77 @@ -['CA'] -'AB' = "Alberta" -'BC' = "British Columbia" -'MB' = "Manitoba" -'NB' = "New Brunswick" -'NF' = "Newfoundland" -'NS' = "Nova Scotia" -'NU' = "Nunavut" -'ON' = "Ontario" -'PE' = "Prince Edward Island" -'QC' = "Quebec" -'SK' = "Saskatchewan" -'NT' = "Northwest Territories" -'YT' = "Yukon Territory" -['US'] -'AA' = "Armed Forces Americas" -'AE' = "Armed Forces Europe, Middle East, & Canada" -'AK' = "Alaska" -'AL' = "Alabama" -'AP' = "Armed Forces Pacific" -'AR' = "Arkansas" -'AS' = "American Samoa" -'AZ' = "Arizona" -'CA' = "California" -'CO' = "Colorado" -'CT' = "Connecticut" -'DC' = "District of Columbia" -'DE' = "Delaware" -'FL' = "Florida" -'FM' = "Federated States of Micronesia" -'GA' = "Georgia" -'GU' = "Guam" -'HI' = "Hawaii" -'IA' = "Iowa" -'ID' = "Idaho" -'IL' = "Illinois" -'IN' = "Indiana" -'KS' = "Kansas" -'KY' = "Kentucky" -'LA' = "Louisiana" -'MA' = "Massachusetts" -'MD' = "Maryland" -'ME' = "Maine" -'MH' = "Marshall Islands" -'MI' = "Michigan" -'MN' = "Minnesota" -'MO' = "Missouri" -'MP' = "Northern Mariana Islands" -'MS' = "Mississippi" -'MT' = "Montana" -'NC' = "North Carolina" -'ND' = "North Dakota" -'NE' = "Nebraska" -'NH' = "New Hampshire" -'NJ' = "New Jersey" -'NM' = "New Mexico" -'NV' = "Nevada" -'NY' = "New York" -'OH' = "Ohio" -'OK' = "Oklahoma" -'OR' = "Oregon" -'PA' = "Pennsylvania" -'PR' = "Puerto Rico" -'PW' = "Palau" -'RI' = "Rhode Island" -'SC' = "South Carolina" -'SD' = "South Dakota" -'TN' = "Tennessee" -'TX' = "Texas" -'UT' = "Utah" -'VA' = "Virginia" -'VI' = "Virgin Islands" -'VT' = "Vermont" -'WA' = "Washington" -'WV' = "West Virginia" -'WI' = "Wisconsin" +['CA'] +'AB' = "Alberta" +'BC' = "British Columbia" +'MB' = "Manitoba" +'NB' = "New Brunswick" +'NF' = "Newfoundland" +'NS' = "Nova Scotia" +'NU' = "Nunavut" +'ON' = "Ontario" +'PE' = "Prince Edward Island" +'QC' = "Quebec" +'SK' = "Saskatchewan" +'NT' = "Northwest Territories" +'YT' = "Yukon Territory" +['US'] +'AA' = "Armed Forces Americas" +'AE' = "Armed Forces Europe, Middle East, & Canada" +'AK' = "Alaska" +'AL' = "Alabama" +'AP' = "Armed Forces Pacific" +'AR' = "Arkansas" +'AS' = "American Samoa" +'AZ' = "Arizona" +'CA' = "California" +'CO' = "Colorado" +'CT' = "Connecticut" +'DC' = "District of Columbia" +'DE' = "Delaware" +'FL' = "Florida" +'FM' = "Federated States of Micronesia" +'GA' = "Georgia" +'GU' = "Guam" +'HI' = "Hawaii" +'IA' = "Iowa" +'ID' = "Idaho" +'IL' = "Illinois" +'IN' = "Indiana" +'KS' = "Kansas" +'KY' = "Kentucky" +'LA' = "Louisiana" +'MA' = "Massachusetts" +'MD' = "Maryland" +'ME' = "Maine" +'MH' = "Marshall Islands" +'MI' = "Michigan" +'MN' = "Minnesota" +'MO' = "Missouri" +'MP' = "Northern Mariana Islands" +'MS' = "Mississippi" +'MT' = "Montana" +'NC' = "North Carolina" +'ND' = "North Dakota" +'NE' = "Nebraska" +'NH' = "New Hampshire" +'NJ' = "New Jersey" +'NM' = "New Mexico" +'NV' = "Nevada" +'NY' = "New York" +'OH' = "Ohio" +'OK' = "Oklahoma" +'OR' = "Oregon" +'PA' = "Pennsylvania" +'PR' = "Puerto Rico" +'PW' = "Palau" +'RI' = "Rhode Island" +'SC' = "South Carolina" +'SD' = "South Dakota" +'TN' = "Tennessee" +'TX' = "Texas" +'UT' = "Utah" +'VA' = "Virginia" +'VI' = "Virgin Islands" +'VT' = "Vermont" +'WA' = "Washington" +'WV' = "West Virginia" +'WI' = "Wisconsin" 'WY' = "Wyoming" \ No newline at end of file diff --git a/modules/maxmind_geoip/includes/maxmind-ws/readme.txt b/modules/maxmind_geoip/includes/maxmind-ws/readme.txt index 06804048a..b8c4e5616 100755 --- a/modules/maxmind_geoip/includes/maxmind-ws/readme.txt +++ b/modules/maxmind_geoip/includes/maxmind-ws/readme.txt @@ -1,83 +1,83 @@ - - -MaxMindWebServices Class -======================== - -The MaxMindWebServices class is an abstract class that all MaxMind web services extend from. This class has no public access. - -I have made a few assumptions in terms of the other services since I have yet to use them. - -1. I assume that all services would have a need to look up: - a. Country Codes - b. SubCountry Codes - c. Metro Codes - - As a result of this assumption I have public methods for translation of these codes in the MaxMindWebServices abstraction class. - -2. Since it appears that not all the Web Services have the same interface I have stored the helper functions in the abstraction class anyway. Reason for this is to reduce code between multiple services. - -Methods that all MaxMind Services have: - setLicenceKey($key) - isError() // return bool - getResultArray() // returns all returned values in an array - lookupCountryCode($countryCode); - lookupSubCountryCode($subcountryCode, $countryCode); - lookupMetroCode($metroCode); - -Notes: - - 1. the lookup...Code() methods use lazy load, they don't parse the ini file unless the method is explicitly call. - - 2. It is possible to set your licenceKey inside this class which then applies it as the default key for all MaxMind web services. - - - -GeoCityLocateIspOrg -=================== - -This class Implements the Geo city location with ISP and Organization inforation included. This class is designed to be used as a singleton. - -ex. - Instead of $service = new GeoCityLocateIspOrg(); - - use: $service = GeoCityLocateIspOrg::getInstance(); - -Methods: - setIP($ip) // this is the trigger, all data is cleared and updated with new value - getIP() - getCountry() - getRegion() - getState() // alias of getRegion() - getCity() - getPostal() - getZip() // alias of getPostal() - getLatitude() - getLat() // alias of getLat() - getLongitude() - getLong() // alias of getLong() - getMetroCode() - getAreaCode() - getISP() - getOrganization() - getError() - - And all generic methods listed above. - - -For Developers -============== - -When adding a new Web Service to this library there are a few code interface details to remember. - -1. All new interfaces must extend MaxMindWebServices -2. All services are responsible for building the url with the query string -3. All services must implement a getError() method -4. All methods must implement there own trigger to submit and recieve data -5. All data recieved must be stored in $this->data array, it doesn't matter if its an assoc array or not. - -TODO -========= - -1. change the _queryMaxMind() in the MaxMindWebService class to handle ssl connections as well. - -2. The ini files that provide the lookup for the country, subcountry and metro codes appears to have issues. In order to remedy the issue I enclosed all keys with tick marks. This issue will be explored later. + + +MaxMindWebServices Class +======================== + +The MaxMindWebServices class is an abstract class that all MaxMind web services extend from. This class has no public access. + +I have made a few assumptions in terms of the other services since I have yet to use them. + +1. I assume that all services would have a need to look up: + a. Country Codes + b. SubCountry Codes + c. Metro Codes + + As a result of this assumption I have public methods for translation of these codes in the MaxMindWebServices abstraction class. + +2. Since it appears that not all the Web Services have the same interface I have stored the helper functions in the abstraction class anyway. Reason for this is to reduce code between multiple services. + +Methods that all MaxMind Services have: + setLicenceKey($key) + isError() // return bool + getResultArray() // returns all returned values in an array + lookupCountryCode($countryCode); + lookupSubCountryCode($subcountryCode, $countryCode); + lookupMetroCode($metroCode); + +Notes: + + 1. the lookup...Code() methods use lazy load, they don't parse the ini file unless the method is explicitly call. + + 2. It is possible to set your licenceKey inside this class which then applies it as the default key for all MaxMind web services. + + + +GeoCityLocateIspOrg +=================== + +This class Implements the Geo city location with ISP and Organization inforation included. This class is designed to be used as a singleton. + +ex. + Instead of $service = new GeoCityLocateIspOrg(); + + use: $service = GeoCityLocateIspOrg::getInstance(); + +Methods: + setIP($ip) // this is the trigger, all data is cleared and updated with new value + getIP() + getCountry() + getRegion() + getState() // alias of getRegion() + getCity() + getPostal() + getZip() // alias of getPostal() + getLatitude() + getLat() // alias of getLat() + getLongitude() + getLong() // alias of getLong() + getMetroCode() + getAreaCode() + getISP() + getOrganization() + getError() + + And all generic methods listed above. + + +For Developers +============== + +When adding a new Web Service to this library there are a few code interface details to remember. + +1. All new interfaces must extend MaxMindWebServices +2. All services are responsible for building the url with the query string +3. All services must implement a getError() method +4. All methods must implement there own trigger to submit and recieve data +5. All data recieved must be stored in $this->data array, it doesn't matter if its an assoc array or not. + +TODO +========= + +1. change the _queryMaxMind() in the MaxMindWebService class to handle ssl connections as well. + +2. The ini files that provide the lookup for the country, subcountry and metro codes appears to have issues. In order to remedy the issue I enclosed all keys with tick marks. This issue will be explored later. diff --git a/modules/maxmind_geoip/module.php b/modules/maxmind_geoip/module.php index bcf3c349e..815de20cf 100644 --- a/modules/maxmind_geoip/module.php +++ b/modules/maxmind_geoip/module.php @@ -26,55 +26,55 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.4.0 + * @version $Revision$ + * @since owa 1.4.0 */ class owa_maxmind_geoipModule extends owa_module { - - var $method; - - function __construct() { - - $this->name = 'maxmind_geoip'; - $this->display_name = 'Maxmind GeoIP'; - $this->group = 'geoip'; - $this->author = 'Peter Adams'; - $this->version = '1.0'; - $this->description = 'Performs Maxmind Geo-IP lookups.'; - $this->config_required = false; - $this->required_schema_version = 1; - - $mode = owa_coreAPI::getSetting('maxmind_geoip', 'lookup_method'); - - switch ( $mode ) { - - case "geoip_city_isp_org_web_service": - $method = 'getLocationFromWebService'; - break; - - case "city_lite_db": - $method = 'getLocation'; - break; - - default: - $method = 'getLocation'; - } - - $this->method = $method; - - // needed so default filters will not fun - owa_coreAPI::setSetting('base', 'geolocation_service', 'maxmind'); - - - return parent::__construct(); - } - - function registerFilters() { - - if ( owa_coreAPI::getSetting('base', 'geolocation_service') === 'maxmind' ) { - - $this->registerFilter('geolocation', 'maxmind', $this->method, 0, 'classes'); - } - } + + var $method; + + function __construct() { + + $this->name = 'maxmind_geoip'; + $this->display_name = 'Maxmind GeoIP'; + $this->group = 'geoip'; + $this->author = 'Peter Adams'; + $this->version = '1.0'; + $this->description = 'Performs Maxmind Geo-IP lookups.'; + $this->config_required = false; + $this->required_schema_version = 1; + + $mode = owa_coreAPI::getSetting('maxmind_geoip', 'lookup_method'); + + switch ( $mode ) { + + case "geoip_city_isp_org_web_service": + $method = 'getLocationFromWebService'; + break; + + case "city_lite_db": + $method = 'getLocation'; + break; + + default: + $method = 'getLocation'; + } + + $this->method = $method; + + // needed so default filters will not fun + owa_coreAPI::setSetting('base', 'geolocation_service', 'maxmind'); + + + return parent::__construct(); + } + + function registerFilters() { + + if ( owa_coreAPI::getSetting('base', 'geolocation_service') === 'maxmind' ) { + + $this->registerFilter('geolocation', 'maxmind', $this->method, 0, 'classes'); + } + } } \ No newline at end of file diff --git a/modules/remoteQueue/module.php b/modules/remoteQueue/module.php index 10078562a..e7ae03d0f 100644 --- a/modules/remoteQueue/module.php +++ b/modules/remoteQueue/module.php @@ -26,36 +26,36 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.5.7 + * @version $Revision$ + * @since owa 1.5.7 */ class owa_remoteQueueModule extends owa_module { - - function __construct() { - - $this->name = 'remoteQueue'; - $this->display_name = 'Remote Queue'; - $this->group = 'logging'; - $this->author = 'Peter Adams'; - $this->version = '1.0'; - $this->description = 'Posts incoming tracking events to a remote instance of OWA'; - $this->config_required = false; - $this->required_schema_version = 1; - - // register named queues - - $endpoint = owa_coreAPI::getSetting( 'remoteQueue', 'endpoint' ); - - if ( $endpoint ) { - - $this->registerEventQueue( 'incoming_tracking_events', array( - - 'queue_type' => 'http', - 'endpoint' => $endpoint - )); - } - - return parent::__construct(); - } + + function __construct() { + + $this->name = 'remoteQueue'; + $this->display_name = 'Remote Queue'; + $this->group = 'logging'; + $this->author = 'Peter Adams'; + $this->version = '1.0'; + $this->description = 'Posts incoming tracking events to a remote instance of OWA'; + $this->config_required = false; + $this->required_schema_version = 1; + + // register named queues + + $endpoint = owa_coreAPI::getSetting( 'remoteQueue', 'endpoint' ); + + if ( $endpoint ) { + + $this->registerEventQueue( 'incoming_tracking_events', array( + + 'queue_type' => 'http', + 'endpoint' => $endpoint + )); + } + + return parent::__construct(); + } } \ No newline at end of file diff --git a/mw_plugin.php b/mw_plugin.php index ff5d10183..6d154b39d 100644 --- a/mw_plugin.php +++ b/mw_plugin.php @@ -1,583 +1,583 @@ - 'Open Web Analytics for MediaWiki', - 'author' => 'Peter Adams', - 'url' => 'http://www.openwebanalytics.com', - 'description' => 'Open Web Analytics for MedaWiki' -); - -// used to sniff out admin requests -$wgHooks['UnknownAction'][] = 'owa_actions'; -// used to set proper params for logging Article Page Views -$wgHooks['ArticlePageDataAfter'][] = 'owa_logArticle'; -// used to set proper params for logging Special Page Views -$wgHooks['SpecialPageExecuteAfterPage'][] = 'owa_logSpecialPage'; -// used to set proper params for logging Category Page Views -$wgHooks['CategoryPageView'][] = 'owa_logCategoryPage'; -// used to add OWA's javascript tracking tag to all pages -$wgHooks['BeforePageDisplay'][] = 'owa_footer'; -// used to fire Action events when articles are created -$wgHooks['ArticleInsertComplete'][] = 'owa_newArticleAction'; -// used to fire Action events when articles are edited -$wgHooks['ArticleSaveComplete'][] = 'owa_editArticleAction'; -// used to fire Action events when new articles are deleted -$wgHooks['ArticleDeleteComplete'][] = 'owa_deleteArticleAction'; -// used to fire Action events when new user accounts are created -$wgHooks['AddNewAccount'][] = 'owa_addUserAction'; -// used to fire Action events when new uploads occur -$wgHooks['UploadComplete'][] = 'owa_addUploadAction'; -// used to fire Action events when users login -$wgHooks['UserLoginComplete'][] = 'owa_userLoginAction'; -// used to fire Action events when talk pages are edited -$wgHooks['ArticleEditUpdateNewTalk'][] ='owa_editTalkPageAction'; -// used to register OWA's special page -$wgHooks['SpecialPage_initList'][] = 'owa_registerSpecialPage'; - -// add 'owa_view' right to admin groups in order to view special page -$wgGroupPermissions['user']['owa_view'] = true; - -/** - * Hook Function for Registering OWA's Special Page - */ -function owa_registerSpecialPage( &$aSpecialPages ) { - - global $wgOwaEnableSpecialPage; - - // Enable Special Page - if ( $wgOwaEnableSpecialPage === true ) { - //Load Special Page - $wgAutoloadClasses['SpecialOwa'] = __FILE__; - // Adds OWA's admin interface to special page list - $aSpecialPages['Owa'] = 'SpecialOwa'; - } - // must return true for hook to continue processing. - return true; -} - -/** - * Hook for OWA special actions - * - * This uses mediawiki's 'unknown action' hook to trigger OWA's special action handler. - * This is setup by adding 'action=owa' to the URLs for special actions. There is - * probably a better way to do this so that the OWA namespace is preserved. - * - * @TODO figure out how to register this method to be triggered only when 'action=owa' instead of - * for all unknown mediawiki actions. - * @param object $specialPage - * @url http://www.mediawiki.org/wiki/Manual:MediaWiki_hooks/UnknownAction - * @return false - */ -function owa_actions($action) { - - global $wgOut, $wgUser, $wgRequest; - - $action = $wgRequest->getText( 'action' ); - if ( $action === 'owa' ) { - $wgOut->disable(); - $owa = owa_singleton(); - $owa->handleSpecialActionRequest(); - return false; - } else { - return true; - } -} - -/** - * OWA Singelton - * - * Needed to avoid OWA loading for every mediawiki request - */ -function owa_singleton() { - - static $owa; - - if ( empty( $owa ) ) { - - global $wgUser, - $wgServer, - $wgScriptPath, - $wgScript, - $wgMainCacheType, - $wgMemCachedServers, - $wgOwaSiteId, - $wgOwaMemCachedServers; - - /* OWA CONFIGURATION OVERRIDES */ - $owa_config = array(); - // check for memcache. these need to be passed into OWA to avoid race condition. - if ( $wgMainCacheType === CACHE_MEMCACHED ) { - $owa_config['cacheType'] = 'memcached'; - $owa_config['memcachedServers'] = $wgMemCachedServers; - } - $owa = new owa_mw( $owa_config ); - $owa->setSetting( 'base', 'report_wrapper', 'wrapper_mediawiki.tpl' ); - $owa->setSetting( 'base', 'main_url', $wgScriptPath.'/index.php?title=Special:Owa' ); - $owa->setSetting( 'base', 'main_absolute_url', $wgServer.$owa->getSetting( 'base', 'main_url' ) ); - $owa->setSetting( 'base', 'action_url', $wgServer.$wgScriptPath.'/index.php?action=owa&owa_specialAction' ); - $owa->setSetting( 'base', 'api_url', $wgServer.$wgScriptPath.'/index.php?action=owa&owa_apiAction' ); - $owa->setSetting( 'base', 'link_template', '%s&%s' ); - $owa->setSetting( 'base', 'is_embedded', true ); - $owa->setSetting( 'base', 'query_string_filters', 'returnto' ); - - if ( ! $wgOwaSiteId ) { - $wgOwaSiteId = md5($wgServer.$wgScriptPath); - } - - $owa->setSiteId( $wgOwaSiteId ); - - // filter authentication - $dispatch = owa_coreAPI::getEventDispatch(); - // alternative auth method, sets auth status, role, and allowed sites list. - $dispatch->attachFilter('auth_status', 'owa_mwAuthUser',0); - //print_r( $current_user ); - - } - - return $owa; -} - -/** - * Populates OWA's current user object with info about the current mediawiki user. - * This info is needed by OWA authentication system as well as to add dimensions - * requests that are logged. - */ -function owa_mwAuthUser($auth_status) { - - global $wgUser, $wgOwaSiteId; - - if ( $wgUser->isLoggedIn() ) { - - $cu = owa_coreAPI::getCurrentUser(); - $cu->setAuthStatus(true); - - $cu->setUserData( 'user_id', $wgUser->getName() ); - $cu->setUserData( 'email_address', $wgUser->getEmail() ); - $cu->setUserData( 'real_name', $wgUser->getRealName() ); - $cu->setRole( owa_translate_role( $wgUser->getGroups() ) ); - - // set list of allowed sites. In this case it's only this wiki. - - $domains = array($wgOwaSiteId); - // load assigned sites list by domain - $cu->loadAssignedSitesByDomain($domains); - $cu->setInitialized(); - - return true; - - } else { - // not logged in - return false; - } - -} - -/** - * Transalates MW Roles into OWA Roles - * - * @todo make this configurable with a global property - */ -function owa_translate_role($level = array()) { - - if ( ! empty( $level ) ) { - - if ( in_array( "*", $level ) ) { - $owa_role = 'everyone'; - } elseif ( in_array( "user", $level ) ) { - $owa_role = 'viewer'; - } elseif ( in_array( "autoconfirmed", $level ) ) { - $owa_role = 'viewer'; - } elseif ( in_array( "emailconfirmed", $level ) ) { - $owa_role = 'viewer'; - } elseif ( in_array( "bot", $level ) ) { - $owa_role = 'viewer'; - } elseif ( in_array( "sysop", $level ) ) { - $owa_role = 'admin'; - } elseif ( in_array( "bureaucrat", $level ) ) { - $owa_role = 'admin'; - } elseif ( in_array( "developer", $level ) ) { - $owa_role = 'admin'; - } - - } else { - $owa_role = ''; - } - - return $owa_role; -} - -/** - * Helper function for tracking page views of various types - */ -function owa_trackPageView( $params = array() ) { - - global $wgUser, $wgOut, $wgOwaSiteId; - - $owa = owa_singleton(); - - if ( $owa->getSetting( 'base', 'install_complete' ) ) { - - //$event = $owa->makeEvent(); - //$event->setEventType( 'base.page_request' ); - $owa->setSiteId( $wgOwaSiteId ); - $owa->setProperty( 'user_name', $wgUser->mName ); - $owa->setProperty( 'user_email', $wgUser->mEmail ); - $owa->setProperty( 'language', owa_getLanguage() ); - if ( ! $owa->pageview_event->get( 'page_type') ) { - $owa->setPageType( '(not set)' ); - } - - //foreach ( $params as $k => $v ) { - // $event->set( $k, $v ); - //} - - // if the page title is not set for some reasons, set it - // using $wgOut. - if ( ! $owa->pageview_event->get( 'page_title') ) { - $owa->setPageTitle( 'page_title', $wgOut->getPageTitle() ); - } - - /* - $tag = sprintf( - ' - var owa_params = %s;', - json_encode( $event->getProperties() ) - ); - - $wgOut->addInlineScript( $tag ); - */ - } - - return true; -} - -/** - * Logs Special Page Views - * - * @param object $specialPage - * @return boolean - */ -function owa_logSpecialPage(&$specialPage) { - - $title_obj = $specialPage->getTitle(); - $title = $title_obj->getText(); - $owa = owa_singleton(); - $owa->setPageTitle( $title ); - $owa->setPageType( 'Special Page' ); - return true; -} - -/** - * Logs Category Page Views - * - * @param object $categoryPage - * @return boolean - */ -function owa_logCategoryPage( &$categoryPage ) { - - $title_obj = $categoryPage->getTitle(); - $title = $title_obj->getText(); - $owa = owa_singleton(); - $owa->setPageTitle( $title ); - $owa->setPageType( 'Category' ); - return true; -} - -/** - * Logs Article Page Views - * - * @param object $article - * @return boolean - */ -function owa_logArticle( &$article ) { - - $title_obj = $article->getTitle(); - $title = $title_obj->getText(); - $owa = owa_singleton(); - $owa->setPageTitle( $title ); - $owa->setPageType( 'Article' ); - return true; -} - -/** - * Helper Function for tracking Action Events - * - * This function is a wrapper for the Action Event API in owa_client. - * - * @param $action_name string The name of the action being tracked - * @param $label string The label associated with the action being tracked - * @return boolean true - */ -function owa_trackAction( $action_name, $label ) { - - $owa = owa_singleton(); - - if ( $owa->getSetting( 'base', 'install_complete' ) ) { - $owa->trackAction( 'mediawiki', $action_name, $label ); - owa_coreAPI::debug( "logging action event " . $action_name ); - } - - return true; -} - -/** - * Logs New Articles - * - * @param object $categoryPage - * @return boolean - */ -function owa_newArticleAction(&$article, &$user, $text, $summary, $minoredit, $watchthis, $sectionanchor, &$flags, $revision) { - - $label = $article->getTitle()->getText(); - return owa_trackAction( 'Article Created', $label ); -} - -function owa_editArticleAction($article, &$user, $text, $summary, - $minoredit, $watchthis, $sectionanchor, &$flags, $revision, - &$status, $baseRevId, &$redirect = '') { - - if ( $flags & EDIT_UPDATE ) { - - $label = $article->getTitle()->getText(); - return owa_trackAction( 'Article Edit', $label ); - - } else { - - return true; - } -} - -function owa_deleteArticleAction( &$article, &$user, $reason, $id ) { - - $label = $article->getTitle()->getText(); - return owa_trackAction( 'Article Deleted', $label ); -} - -function owa_addUserAction( $user, $byEmail ) { - - $label = ''; - return owa_trackAction( 'User Account Added', $label ); -} - -function owa_addUploadAction( &$image ) { - - $label = $image->getLocalFile()->getMimeType(); - return owa_trackAction( 'File Upload', $label ); -} - -function owa_userLoginAction( &$user, &$inject_html ) { - - $label = ''; - return owa_trackAction( 'Login', $label ); -} - -function editTalkPageAction( $article ) { - - $label = $article->getTitle()->getText(); - return owa_trackAction( 'Talk Page Edit', $label ); -} - -/** - * Adds javascript tracker to pages - * - * @param object $article - * @return boolean - */ -function owa_footer(&$wgOut, $sk) { - - global $wgRequest, $wgOwaThirdPartyCookies, $wgOwaCookieDomain; - - if ($wgRequest->getVal('action') != 'edit' && $wgRequest->getVal('title') != 'Special:Owa') { - - $owa = owa_singleton(); - if ($owa->getSetting('base', 'install_complete')) { - - $cmds = ""; - if ( $wgOwaThirdPartyCookies ) { - $cmds .= "owa_cmds.push( ['setOption', 'thirdParty', true] );"; - } - - if ( $wgOwaCookieDomain ) { - $cmds .= "owa_cmds.push( ['setCookieDomain', '$wgOwaCookieDomain'] );"; - } - - $page_properties = $owa->getAllEventProperties($owa->pageview_event); - if ( $page_properties ) { - $page_properties_json = json_encode( $page_properties ); - $cmds .= "owa_cmds.push( ['setPageProperties', $page_properties_json] );"; - } - - //$wgOut->addInlineScript( $cmds ); - - $options = array( 'cmds' => $cmds ); - - $tags = $owa->placeHelperPageTags(false, $options); - $wgOut->addHTML($tags); - - } - } - - return true; -} - -/** - * Gets mediawiki Language variable - */ -function owa_getLanguage() { - - global $wgLang, $wgContLang; - $code = ''; - - $code = $wgLang->getCode(); - if ( ! $code ) { - $code = $wgContLang->getCode(); - } - - return $code; -} - -/** - * OWA Special Page Class - * - * Enables OWA to be accessed through a Mediawiki special page. - */ -class SpecialOwa extends SpecialPage { - - function __construct() { - parent::SpecialPage('Owa', 'owa_view'); - self::loadMessages(); - } - - function execute() { - - global $wgRequest, $wgOut, $wgUser, $wgSitename, $wgScriptPath, $wgScript, $wgServer, - $wgDBtype, $wgDBname, $wgDBserver, $wgDBuser, $wgDBpassword; - - //must be called after setHeaders for some reason or elsethe wgUser object is not yet populated. - $this->setHeaders(); - - if ($this->userCanExecute($wgUser)) { - - - $owa = owa_singleton(); - $params = array(); - - // if no action is found... - $do = owa_coreAPI::getRequestParam('do'); - if (empty($do)) { - // check to see that owa in installed. - if (!$owa->getSetting('base', 'install_complete')) { - - define('OWA_INSTALLING', true); - - $site_url = $wgServer.$wgScriptPath; - - $params = array( - 'site_id' => md5($site_url), - 'name' => $wgSitename, - 'domain' => $site_url, - 'description' => '', - 'do' => 'base.installStartEmbedded'); - - $params['db_type'] = $wgDBtype; - $params['db_name'] = $wgDBname; - $params['db_host'] = $wgDBserver; - $params['db_user'] = $wgDBuser; - $params['db_password'] = $wgDBpassword; - $params['public_url'] = $wgServer.$wgScriptPath.'/extensions/owa/'; - $page = $owa->handleRequest($params); - - // send to daashboard - } else { - //$params['do'] = 'base.reportDashboard'; - - $page = $owa->handleRequest($params); - } - // do action found on url - } else { - $page = $owa->handleRequestFromURL(); - } - - return $wgOut->addHTML($page); - } else { - $this->displayRestrictionError(); - } - } - - function loadMessages() { - static $messagesLoaded = false; - global $wgMessageCache; - - if ( $messagesLoaded ) return; - - $messagesLoaded = true; - - // this should be the only msg defined by mediawiki - $allMessages = array( - 'en' => array( - 'owa' => 'Open Web Analytics' - ) - ); - - - // load msgs in to mediawiki cache - foreach ( $allMessages as $lang => $langMessages ) { - $wgMessageCache->addMessages( $langMessages, $lang ); - } - - return true; - } -} - -?> + 'Open Web Analytics for MediaWiki', + 'author' => 'Peter Adams', + 'url' => 'http://www.openwebanalytics.com', + 'description' => 'Open Web Analytics for MedaWiki' +); + +// used to sniff out admin requests +$wgHooks['UnknownAction'][] = 'owa_actions'; +// used to set proper params for logging Article Page Views +$wgHooks['ArticlePageDataAfter'][] = 'owa_logArticle'; +// used to set proper params for logging Special Page Views +$wgHooks['SpecialPageExecuteAfterPage'][] = 'owa_logSpecialPage'; +// used to set proper params for logging Category Page Views +$wgHooks['CategoryPageView'][] = 'owa_logCategoryPage'; +// used to add OWA's javascript tracking tag to all pages +$wgHooks['BeforePageDisplay'][] = 'owa_footer'; +// used to fire Action events when articles are created +$wgHooks['ArticleInsertComplete'][] = 'owa_newArticleAction'; +// used to fire Action events when articles are edited +$wgHooks['ArticleSaveComplete'][] = 'owa_editArticleAction'; +// used to fire Action events when new articles are deleted +$wgHooks['ArticleDeleteComplete'][] = 'owa_deleteArticleAction'; +// used to fire Action events when new user accounts are created +$wgHooks['AddNewAccount'][] = 'owa_addUserAction'; +// used to fire Action events when new uploads occur +$wgHooks['UploadComplete'][] = 'owa_addUploadAction'; +// used to fire Action events when users login +$wgHooks['UserLoginComplete'][] = 'owa_userLoginAction'; +// used to fire Action events when talk pages are edited +$wgHooks['ArticleEditUpdateNewTalk'][] ='owa_editTalkPageAction'; +// used to register OWA's special page +$wgHooks['SpecialPage_initList'][] = 'owa_registerSpecialPage'; + +// add 'owa_view' right to admin groups in order to view special page +$wgGroupPermissions['user']['owa_view'] = true; + +/** + * Hook Function for Registering OWA's Special Page + */ +function owa_registerSpecialPage( &$aSpecialPages ) { + + global $wgOwaEnableSpecialPage; + + // Enable Special Page + if ( $wgOwaEnableSpecialPage === true ) { + //Load Special Page + $wgAutoloadClasses['SpecialOwa'] = __FILE__; + // Adds OWA's admin interface to special page list + $aSpecialPages['Owa'] = 'SpecialOwa'; + } + // must return true for hook to continue processing. + return true; +} + +/** + * Hook for OWA special actions + * + * This uses mediawiki's 'unknown action' hook to trigger OWA's special action handler. + * This is setup by adding 'action=owa' to the URLs for special actions. There is + * probably a better way to do this so that the OWA namespace is preserved. + * + * @TODO figure out how to register this method to be triggered only when 'action=owa' instead of + * for all unknown mediawiki actions. + * @param object $specialPage + * @url http://www.mediawiki.org/wiki/Manual:MediaWiki_hooks/UnknownAction + * @return false + */ +function owa_actions($action) { + + global $wgOut, $wgUser, $wgRequest; + + $action = $wgRequest->getText( 'action' ); + if ( $action === 'owa' ) { + $wgOut->disable(); + $owa = owa_singleton(); + $owa->handleSpecialActionRequest(); + return false; + } else { + return true; + } +} + +/** + * OWA Singelton + * + * Needed to avoid OWA loading for every mediawiki request + */ +function owa_singleton() { + + static $owa; + + if ( empty( $owa ) ) { + + global $wgUser, + $wgServer, + $wgScriptPath, + $wgScript, + $wgMainCacheType, + $wgMemCachedServers, + $wgOwaSiteId, + $wgOwaMemCachedServers; + + /* OWA CONFIGURATION OVERRIDES */ + $owa_config = array(); + // check for memcache. these need to be passed into OWA to avoid race condition. + if ( $wgMainCacheType === CACHE_MEMCACHED ) { + $owa_config['cacheType'] = 'memcached'; + $owa_config['memcachedServers'] = $wgMemCachedServers; + } + $owa = new owa_mw( $owa_config ); + $owa->setSetting( 'base', 'report_wrapper', 'wrapper_mediawiki.tpl' ); + $owa->setSetting( 'base', 'main_url', $wgScriptPath.'/index.php?title=Special:Owa' ); + $owa->setSetting( 'base', 'main_absolute_url', $wgServer.$owa->getSetting( 'base', 'main_url' ) ); + $owa->setSetting( 'base', 'action_url', $wgServer.$wgScriptPath.'/index.php?action=owa&owa_specialAction' ); + $owa->setSetting( 'base', 'api_url', $wgServer.$wgScriptPath.'/index.php?action=owa&owa_apiAction' ); + $owa->setSetting( 'base', 'link_template', '%s&%s' ); + $owa->setSetting( 'base', 'is_embedded', true ); + $owa->setSetting( 'base', 'query_string_filters', 'returnto' ); + + if ( ! $wgOwaSiteId ) { + $wgOwaSiteId = md5($wgServer.$wgScriptPath); + } + + $owa->setSiteId( $wgOwaSiteId ); + + // filter authentication + $dispatch = owa_coreAPI::getEventDispatch(); + // alternative auth method, sets auth status, role, and allowed sites list. + $dispatch->attachFilter('auth_status', 'owa_mwAuthUser',0); + //print_r( $current_user ); + + } + + return $owa; +} + +/** + * Populates OWA's current user object with info about the current mediawiki user. + * This info is needed by OWA authentication system as well as to add dimensions + * requests that are logged. + */ +function owa_mwAuthUser($auth_status) { + + global $wgUser, $wgOwaSiteId; + + if ( $wgUser->isLoggedIn() ) { + + $cu = owa_coreAPI::getCurrentUser(); + $cu->setAuthStatus(true); + + $cu->setUserData( 'user_id', $wgUser->getName() ); + $cu->setUserData( 'email_address', $wgUser->getEmail() ); + $cu->setUserData( 'real_name', $wgUser->getRealName() ); + $cu->setRole( owa_translate_role( $wgUser->getGroups() ) ); + + // set list of allowed sites. In this case it's only this wiki. + + $domains = array($wgOwaSiteId); + // load assigned sites list by domain + $cu->loadAssignedSitesByDomain($domains); + $cu->setInitialized(); + + return true; + + } else { + // not logged in + return false; + } + +} + +/** + * Transalates MW Roles into OWA Roles + * + * @todo make this configurable with a global property + */ +function owa_translate_role($level = array()) { + + if ( ! empty( $level ) ) { + + if ( in_array( "*", $level ) ) { + $owa_role = 'everyone'; + } elseif ( in_array( "user", $level ) ) { + $owa_role = 'viewer'; + } elseif ( in_array( "autoconfirmed", $level ) ) { + $owa_role = 'viewer'; + } elseif ( in_array( "emailconfirmed", $level ) ) { + $owa_role = 'viewer'; + } elseif ( in_array( "bot", $level ) ) { + $owa_role = 'viewer'; + } elseif ( in_array( "sysop", $level ) ) { + $owa_role = 'admin'; + } elseif ( in_array( "bureaucrat", $level ) ) { + $owa_role = 'admin'; + } elseif ( in_array( "developer", $level ) ) { + $owa_role = 'admin'; + } + + } else { + $owa_role = ''; + } + + return $owa_role; +} + +/** + * Helper function for tracking page views of various types + */ +function owa_trackPageView( $params = array() ) { + + global $wgUser, $wgOut, $wgOwaSiteId; + + $owa = owa_singleton(); + + if ( $owa->getSetting( 'base', 'install_complete' ) ) { + + //$event = $owa->makeEvent(); + //$event->setEventType( 'base.page_request' ); + $owa->setSiteId( $wgOwaSiteId ); + $owa->setProperty( 'user_name', $wgUser->mName ); + $owa->setProperty( 'user_email', $wgUser->mEmail ); + $owa->setProperty( 'language', owa_getLanguage() ); + if ( ! $owa->pageview_event->get( 'page_type') ) { + $owa->setPageType( '(not set)' ); + } + + //foreach ( $params as $k => $v ) { + // $event->set( $k, $v ); + //} + + // if the page title is not set for some reasons, set it + // using $wgOut. + if ( ! $owa->pageview_event->get( 'page_title') ) { + $owa->setPageTitle( 'page_title', $wgOut->getPageTitle() ); + } + + /* + $tag = sprintf( + ' + var owa_params = %s;', + json_encode( $event->getProperties() ) + ); + + $wgOut->addInlineScript( $tag ); + */ + } + + return true; +} + +/** + * Logs Special Page Views + * + * @param object $specialPage + * @return boolean + */ +function owa_logSpecialPage(&$specialPage) { + + $title_obj = $specialPage->getTitle(); + $title = $title_obj->getText(); + $owa = owa_singleton(); + $owa->setPageTitle( $title ); + $owa->setPageType( 'Special Page' ); + return true; +} + +/** + * Logs Category Page Views + * + * @param object $categoryPage + * @return boolean + */ +function owa_logCategoryPage( &$categoryPage ) { + + $title_obj = $categoryPage->getTitle(); + $title = $title_obj->getText(); + $owa = owa_singleton(); + $owa->setPageTitle( $title ); + $owa->setPageType( 'Category' ); + return true; +} + +/** + * Logs Article Page Views + * + * @param object $article + * @return boolean + */ +function owa_logArticle( &$article ) { + + $title_obj = $article->getTitle(); + $title = $title_obj->getText(); + $owa = owa_singleton(); + $owa->setPageTitle( $title ); + $owa->setPageType( 'Article' ); + return true; +} + +/** + * Helper Function for tracking Action Events + * + * This function is a wrapper for the Action Event API in owa_client. + * + * @param $action_name string The name of the action being tracked + * @param $label string The label associated with the action being tracked + * @return boolean true + */ +function owa_trackAction( $action_name, $label ) { + + $owa = owa_singleton(); + + if ( $owa->getSetting( 'base', 'install_complete' ) ) { + $owa->trackAction( 'mediawiki', $action_name, $label ); + owa_coreAPI::debug( "logging action event " . $action_name ); + } + + return true; +} + +/** + * Logs New Articles + * + * @param object $categoryPage + * @return boolean + */ +function owa_newArticleAction(&$article, &$user, $text, $summary, $minoredit, $watchthis, $sectionanchor, &$flags, $revision) { + + $label = $article->getTitle()->getText(); + return owa_trackAction( 'Article Created', $label ); +} + +function owa_editArticleAction($article, &$user, $text, $summary, + $minoredit, $watchthis, $sectionanchor, &$flags, $revision, + &$status, $baseRevId, &$redirect = '') { + + if ( $flags & EDIT_UPDATE ) { + + $label = $article->getTitle()->getText(); + return owa_trackAction( 'Article Edit', $label ); + + } else { + + return true; + } +} + +function owa_deleteArticleAction( &$article, &$user, $reason, $id ) { + + $label = $article->getTitle()->getText(); + return owa_trackAction( 'Article Deleted', $label ); +} + +function owa_addUserAction( $user, $byEmail ) { + + $label = ''; + return owa_trackAction( 'User Account Added', $label ); +} + +function owa_addUploadAction( &$image ) { + + $label = $image->getLocalFile()->getMimeType(); + return owa_trackAction( 'File Upload', $label ); +} + +function owa_userLoginAction( &$user, &$inject_html ) { + + $label = ''; + return owa_trackAction( 'Login', $label ); +} + +function editTalkPageAction( $article ) { + + $label = $article->getTitle()->getText(); + return owa_trackAction( 'Talk Page Edit', $label ); +} + +/** + * Adds javascript tracker to pages + * + * @param object $article + * @return boolean + */ +function owa_footer(&$wgOut, $sk) { + + global $wgRequest, $wgOwaThirdPartyCookies, $wgOwaCookieDomain; + + if ($wgRequest->getVal('action') != 'edit' && $wgRequest->getVal('title') != 'Special:Owa') { + + $owa = owa_singleton(); + if ($owa->getSetting('base', 'install_complete')) { + + $cmds = ""; + if ( $wgOwaThirdPartyCookies ) { + $cmds .= "owa_cmds.push( ['setOption', 'thirdParty', true] );"; + } + + if ( $wgOwaCookieDomain ) { + $cmds .= "owa_cmds.push( ['setCookieDomain', '$wgOwaCookieDomain'] );"; + } + + $page_properties = $owa->getAllEventProperties($owa->pageview_event); + if ( $page_properties ) { + $page_properties_json = json_encode( $page_properties ); + $cmds .= "owa_cmds.push( ['setPageProperties', $page_properties_json] );"; + } + + //$wgOut->addInlineScript( $cmds ); + + $options = array( 'cmds' => $cmds ); + + $tags = $owa->placeHelperPageTags(false, $options); + $wgOut->addHTML($tags); + + } + } + + return true; +} + +/** + * Gets mediawiki Language variable + */ +function owa_getLanguage() { + + global $wgLang, $wgContLang; + $code = ''; + + $code = $wgLang->getCode(); + if ( ! $code ) { + $code = $wgContLang->getCode(); + } + + return $code; +} + +/** + * OWA Special Page Class + * + * Enables OWA to be accessed through a Mediawiki special page. + */ +class SpecialOwa extends SpecialPage { + + function __construct() { + parent::SpecialPage('Owa', 'owa_view'); + self::loadMessages(); + } + + function execute() { + + global $wgRequest, $wgOut, $wgUser, $wgSitename, $wgScriptPath, $wgScript, $wgServer, + $wgDBtype, $wgDBname, $wgDBserver, $wgDBuser, $wgDBpassword; + + //must be called after setHeaders for some reason or elsethe wgUser object is not yet populated. + $this->setHeaders(); + + if ($this->userCanExecute($wgUser)) { + + + $owa = owa_singleton(); + $params = array(); + + // if no action is found... + $do = owa_coreAPI::getRequestParam('do'); + if (empty($do)) { + // check to see that owa in installed. + if (!$owa->getSetting('base', 'install_complete')) { + + define('OWA_INSTALLING', true); + + $site_url = $wgServer.$wgScriptPath; + + $params = array( + 'site_id' => md5($site_url), + 'name' => $wgSitename, + 'domain' => $site_url, + 'description' => '', + 'do' => 'base.installStartEmbedded'); + + $params['db_type'] = $wgDBtype; + $params['db_name'] = $wgDBname; + $params['db_host'] = $wgDBserver; + $params['db_user'] = $wgDBuser; + $params['db_password'] = $wgDBpassword; + $params['public_url'] = $wgServer.$wgScriptPath.'/extensions/owa/'; + $page = $owa->handleRequest($params); + + // send to daashboard + } else { + //$params['do'] = 'base.reportDashboard'; + + $page = $owa->handleRequest($params); + } + // do action found on url + } else { + $page = $owa->handleRequestFromURL(); + } + + return $wgOut->addHTML($page); + } else { + $this->displayRestrictionError(); + } + } + + function loadMessages() { + static $messagesLoaded = false; + global $wgMessageCache; + + if ( $messagesLoaded ) return; + + $messagesLoaded = true; + + // this should be the only msg defined by mediawiki + $allMessages = array( + 'en' => array( + 'owa' => 'Open Web Analytics' + ) + ); + + + // load msgs in to mediawiki cache + foreach ( $allMessages as $lang => $langMessages ) { + $wgMessageCache->addMessages( $langMessages, $lang ); + } + + return true; + } +} + +?> diff --git a/owa-config-dist.php b/owa-config-dist.php index bc41702f1..03ea48920 100644 --- a/owa-config-dist.php +++ b/owa-config-dist.php @@ -1,103 +1,103 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -/** - * DATABASE CONFIGURATION - * - * Connection info for databases that will be used by OWA. - * - */ - -define('OWA_DB_TYPE', 'yourdbtypegoeshere'); // options: mysql -define('OWA_DB_NAME', 'yourdbnamegoeshere'); // name of the database -define('OWA_DB_HOST', 'yourdbhostgoeshere'); // host name of the server housing the database -define('OWA_DB_USER', 'yourdbusergoeshere'); // database user -define('OWA_DB_PORT', '3306'); // port of database -define('OWA_DB_PASSWORD', 'yourdbpasswordgoeshere'); // database user's password - -/** - * AUTHENTICATION KEYS AND SALTS - * - * Change these to different unique phrases. - */ -define('OWA_NONCE_KEY', 'yournoncekeygoeshere'); -define('OWA_NONCE_SALT', 'yournoncesaltgoeshere'); -define('OWA_AUTH_KEY', 'yourauthkeygoeshere'); -define('OWA_AUTH_SALT', 'yourauthsaltgoeshere'); - -/** - * PUBLIC URL - * - * Define the URL of OWA's base directory e.g. http://www.domain.com/path/to/owa/ - * Don't forget the slash at the end. - */ - -define('OWA_PUBLIC_URL', 'http://domain/path/to/owa/'); - -/** - * OWA ERROR HANDLER - * - * Overide OWA error handler. This should be done through the admin GUI, but - * can be handy during install or development. - * - * Choices are: - * - * 'production' - will log only critical errors to a log file. - * 'development' - logs al sorts of useful debug to log file. - */ - -//define('OWA_ERROR_HANDLER', 'development'); - -/** - * LOG PHP ERRORS - * - * Log all php errors to OWA's error log file. Only do this to debug. - */ - -//define('OWA_LOG_PHP_ERRORS', true); - -/** - * OBJECT CACHING - * - * Override setting to cache objects. Caching will increase performance. - */ - -//define('OWA_CACHE_OBJECTS', true); - -/** - * CONFIGURATION ID - * - * Override to load an alternative user configuration - */ - -//define('OWA_CONFIGURATION_ID', '1'); - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +/** + * DATABASE CONFIGURATION + * + * Connection info for databases that will be used by OWA. + * + */ + +define('OWA_DB_TYPE', 'yourdbtypegoeshere'); // options: mysql +define('OWA_DB_NAME', 'yourdbnamegoeshere'); // name of the database +define('OWA_DB_HOST', 'yourdbhostgoeshere'); // host name of the server housing the database +define('OWA_DB_USER', 'yourdbusergoeshere'); // database user +define('OWA_DB_PORT', '3306'); // port of database +define('OWA_DB_PASSWORD', 'yourdbpasswordgoeshere'); // database user's password + +/** + * AUTHENTICATION KEYS AND SALTS + * + * Change these to different unique phrases. + */ +define('OWA_NONCE_KEY', 'yournoncekeygoeshere'); +define('OWA_NONCE_SALT', 'yournoncesaltgoeshere'); +define('OWA_AUTH_KEY', 'yourauthkeygoeshere'); +define('OWA_AUTH_SALT', 'yourauthsaltgoeshere'); + +/** + * PUBLIC URL + * + * Define the URL of OWA's base directory e.g. http://www.domain.com/path/to/owa/ + * Don't forget the slash at the end. + */ + +define('OWA_PUBLIC_URL', 'http://domain/path/to/owa/'); + +/** + * OWA ERROR HANDLER + * + * Overide OWA error handler. This should be done through the admin GUI, but + * can be handy during install or development. + * + * Choices are: + * + * 'production' - will log only critical errors to a log file. + * 'development' - logs al sorts of useful debug to log file. + */ + +//define('OWA_ERROR_HANDLER', 'development'); + +/** + * LOG PHP ERRORS + * + * Log all php errors to OWA's error log file. Only do this to debug. + */ + +//define('OWA_LOG_PHP_ERRORS', true); + +/** + * OBJECT CACHING + * + * Override setting to cache objects. Caching will increase performance. + */ + +//define('OWA_CACHE_OBJECTS', true); + +/** + * CONFIGURATION ID + * + * Override to load an alternative user configuration + */ + +//define('OWA_CONFIGURATION_ID', '1'); + + ?> \ No newline at end of file diff --git a/owa_adminController.php b/owa_adminController.php index d5b1f18e2..cd8d1bb32 100644 --- a/owa_adminController.php +++ b/owa_adminController.php @@ -1,52 +1,52 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - -class owa_adminController extends owa_controller { - - var $is_admin = true; - - /** - * Constructor - * - * @param array $params - * @return owa_controller - */ - function __construct($params) { - - return parent::__construct($params); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + +class owa_adminController extends owa_controller { + + var $is_admin = true; + + /** + * Constructor + * + * @param array $params + * @return owa_controller + */ + function __construct($params) { + + return parent::__construct($params); + } +} + ?> \ No newline at end of file diff --git a/owa_auth.php b/owa_auth.php index d1933f3cd..6f428dea6 100644 --- a/owa_auth.php +++ b/owa_auth.php @@ -1,490 +1,490 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_auth extends owa_base { - - /** - * User object - * - * @var unknown_type - */ - var $u; - - /** - * Array of permission roles that users can have - * - * @var array - */ - var $roles; - - var $status_msg; - - /** - * Login credentials - * - * @var array - */ - var $credentials = array(); - - /** - * Status of Authentication - * - * @var boolean - */ - var $auth_status = false; - - var $_is_user = false; - - var $_priviledge_level; - - var $_is_priviledged = false; - - var $params; - - var $check_for_credentials = false; - - /** - * Auth class Singleton - * - * @return owa_auth - */ - public static function get_instance($plugin = '') { - - static $auth; - - if (!$auth) { - - $auth = new owa_auth(); - - } - - return $auth; - } - - - /** - * Class Constructor - * - * @return owa_auth - */ - function __construct() { - - // register auth cookies - owa_coreAPI::registerStateStore('u', time()+3600*24*365*10, '', '', 'cookie'); - owa_coreAPI::registerStateStore('p', time()+3600*2, '', '', 'cookie'); - - parent::__construct(); - $this->eq = owa_coreAPI::getEventDispatch(); - } - - /** - * Used by controllers to check if the user exists and if they are priviledged. - * - * @param string $necessary_role - */ - function authenticateUser() { - - // check existing auth status first in case someone else took care of this already. - if (owa_coreAPI::getCurrentUser()->isAuthenticated()) { - $ret = true; - } elseif (owa_coreAPI::getRequestParam('apiKey')) { - // auth user by api key - $ret = $this->authByApiKey(owa_coreAPI::getRequestParam('apiKey')); - } elseif (owa_coreAPI::getRequestParam('pk') && owa_coreAPI::getStateParam('u')) { - // auth user by temporary passkey. used in forgot password situations - $ret = $this->authenticateUserByUrlPasskey(owa_coreAPI::getRequestParam('pk')); - } elseif (owa_coreAPI::getRequestParam('user_id') && owa_coreAPI::getRequestParam('password')) { - // auth user by login form input - $ret = $this->authByInput(owa_coreAPI::getRequestParam('user_id'), owa_coreAPI::getRequestParam('password')); - } elseif (owa_coreAPI::getStateParam('u') && owa_coreAPI::getStateParam('p')) { - // auth user by cookies - $ret = $this->authByCookies(owa_coreAPI::getStateParam('u'), owa_coreAPI::getStateParam('p')); - // bump expiration time - //owa_coreAPI::setState('p', '', owa_coreAPI::getStateParam('p')); - } else { - $ret = false; - owa_coreAPI::debug("Could not find any credentials to authenticate with."); - } - - // filter results for modules can add their own auth logic. - $ret = $this->eq->filter('auth_status', $ret); - - return array('auth_status' => $ret); - - } - - function authByApiKey( $key ) { - - $key = owa_sanitize::cleanMd5( $key ); - - if ( $key ) { - - // fetch user object from the db - $this->u = owa_coreAPI::entityFactory('base.user'); - $this->u->load($key, 'api_key'); - - if ($this->u->get('user_id')) { - // get current user - $cu = owa_coreAPI::getCurrentUser(); - // set as new current user in service layer - $cu->loadNewUserByObject($this->u); - $cu->setAuthStatus(true); - $this->_is_user = true; - return true; - } else { - return false; - } - - } else { - - return false; - } - - } - - function authByCookies($user_id, $password) { - - // set credentials - $this->credentials['user_id'] = owa_sanitize::cleanUserId( $user_id ); - $this->credentials['password'] = $password; - - // lookup user if not already done. - if ($this->_is_user == false) { - - // check to see if the current user has already been authenticated by something upstream - $cu = owa_coreAPI::getCurrentUser(); - if (!$cu->isAuthenticated()) { - // check to see if they are a user. - $val = $this->isUser(); - //print ("val: ". $val); - return $val; - } - } else { - return true; - } - } - - function authByInput($user_id, $password) { - - // set credentials - $this->credentials['user_id'] = owa_sanitize::cleanUserId( $user_id ); - // must encrypt password to see if it matches whats in the db - $this->credentials['password'] = $this->generateAuthCredential( $this->credentials['user_id'], $this->encryptOldPassword( $password ) ); - // pass plain text password to test with password_verify - $this->credentials['new_password'] = $password; - //owa_coreAPI::debug(print_r($this->credentials, true)); - $ret = $this->isUser(); - - if ($ret === true) { - $this->saveCredentials(); - } - - return $ret; - } - - /** - * Looks up user by temporary Passkey Column in db - * - * @param unknown_type $key - * @return unknown - */ - function authenticateUserTempPasskey( $key ) { - - $key = owa_sanitize::cleanMd5( $key ); - - if ( $key ) { - - $this->u = owa_coreAPI::entityFactory('base.user'); - $this->u->getByColumn('temp_passkey', $key); - - $id = $this->u->get('id'); - - if (!empty($id)) { - - return true; - - } else { - - return false; - } - - } else { - - return false; - } - } - - /** - * Authenticates user by a passkey - * - * @param unknown_type $key - * @return unknown - */ - function authenticateUserByUrlPasskey($user_id, $passkey) { - - $passkey = owa_sanitize::cleanMd5( $passkey ); - - if ( $passkey ) { - - // set credentials - $this->credentials['user_id'] = $user_id; - $this->credentials['passkey'] = $passkey; - - // fetch user obj - $this->getUser(); - - // generate a new passkey from its components in the db - $key = $this->generateUrlPasskey($this->u->get('user_id'), $this->u->get('password')); - - // see if it matches the key on the url - if ($key == $passkey) { - - return true; - - } else { - return false; - } - - } else { - - return false; - } - } - - /** - * Sets a temporary Passkey for a user - * - * @param string $email_address - * @return boolean - */ - function setTempPasskey($email_address) { - - $this->u = owa_coreAPI::entityFactory('base.user'); - $this->u->getByColumn('email_address', $email_address); - - $id = $u->get('id'); - - if (!empty($id)): - - $this->eq->log(array('email_address' => $this->u->email_address), 'user.set_temp_passkey'); - return true; - else: - return false; - endif; - - } - - function generateTempPasskey($seed) { - - return md5($seed.time().rand()); - } - - function generateUrlPasskey($user_name, $password) { - - return md5($user_name . $password); - - } - - /** - * Sets the initial Passkey for a new user - * - * @param string $user_id - * @return boolean - * @deprecated - */ - function setInitialPasskey($user_id) { - - return $this->eq->log(array('user_id' => $user_id), 'user.set_initial_passkey'); - - } - - /** - * Saves login credentails to persistant browser cookies - * TODO: refactor to use state facility - */ - function saveCredentials() { - - $this->e->debug('saving user credentials to cookies'); - - if (PHP_VERSION_ID < 70300) { - setcookie($this->config['ns'].'u', $this->u->get('user_id'), time()+3600*24*365*10, '/; samesite=None', $this->config['cookie_domain']); - setcookie($this->config['ns'].'p', $this->generateAuthCredential( $this->credentials['user_id'], $this->u->get('password') ), time()+3600*24*2, '/; samesite=None', $this->config['cookie_domain']); - } else { - setcookie($this->config['ns'].'u', $this->u->get('user_id'), [ - 'expires' => time()+3600*24*365*10, - 'path' => '/', - 'samesite' => 'None', - 'domain' => $this->config['cookie_domain'], - ]); - setcookie($this->config['ns'].'p', $this->generateAuthCredential( $this->credentials['user_id'], $this->u->get('password') ), [ - 'expires' => time()+3600*24*365*10, - 'path' => '/', - 'samesite' => 'None', - 'domain' => $this->config['cookie_domain'], - ]); - } - } - - /** - * Removes credentials - * @return boolean - */ - function deleteCredentials() { - - return owa_coreAPI::clearState('p'); - } - - /** - * Simple Password Encryption Scheme - * - * @param string $password - * @return string - */ - function encryptPassword($password) { - - return owa_lib::encryptPassword($password); - - } - function encryptOldPassword($password) { - - return owa_lib::encryptOldPassword($password); - - } - - function getUser() { - - // fetch user object from the db - $this->u = owa_coreAPI::entityFactory('base.user'); - $this->u->getByColumn('user_id', $this->credentials['user_id']); - } - - /** - * Checks to see if the user credentials match a real user object in the DB - * - * @return boolean - */ - function isUser() { - - // get current user - $cu = owa_coreAPI::getCurrentUser(); - - // fetches user object from DB - $this->getUser(); - - if ( $this->credentials['user_id'] === $this->u->get('user_id') ) { - - // new_password will only be set when using authByInput - if ( isset($this->credentials['new_password']) ) { - // plain text password matches DB password we can authorize - if ( password_verify( $this->credentials['new_password'], $this->u->get('password') ) ) { - $this->_is_user = true; - - // set as new current user in service layer - $cu->loadNewUserByObject( $this->u ); - $cu->setAuthStatus(true); - - return true; - } - } - - //if ($this->credentials['password'] === $this->u->get('password')): - if ( $this->isValidAuthCredential( $this->credentials['user_id'], $this->credentials['password'] ) ) { - $this->_is_user = true; - - // set as new current user in service layer - $cu->loadNewUserByObject( $this->u ); - $cu->setAuthStatus(true); - - return true; - } else { - $this->_is_user = false; - return false; - } - } else { - $this->_is_user = false; - return false; - } - } - - function isValidAuthCredential( $user_id, $passed_credential ) { - - $hash = ''; - $hash = $this->reconstructAuthCredential( $user_id ); - //print "hash: $hash "; - //print "passed credential: $passed_credential "; - if ( function_exists('hash_equals') ) { - - return hash_equals( $hash, $passed_credential ); - - } else { - - if ( $hash === $passed_credential ) { - - return true; - } - } - } - - function reconstructAuthCredential( $user_id ) { - - $u = owa_coreAPI::entityFactory('base.user'); - - $u->getByColumn( 'user_id', $user_id ); - - $password = $u->get('password'); - //print "password $password"; - return $this->generateAuthCredential( $user_id, $password ); - } - - function generateAuthCredential($user_id, $password, $expiration = '', $scheme = 'auth') { - - $frag = substr($password, 8, 4); - - $key = owa_coreAPI::saltedHash( $user_id . $frag . $expiration, $scheme ); - - $algo = 'sha1'; - - if ( function_exists( 'hash' ) ) { - - $algo = 'sha256'; - - } - - $hash = owa_lib::hash( $algo, $user_id . $expiration, $key ); - - $credential = $hash; // could add other elements here. - - return $credential; - } - -} - -?> + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_auth extends owa_base { + + /** + * User object + * + * @var unknown_type + */ + var $u; + + /** + * Array of permission roles that users can have + * + * @var array + */ + var $roles; + + var $status_msg; + + /** + * Login credentials + * + * @var array + */ + var $credentials = array(); + + /** + * Status of Authentication + * + * @var boolean + */ + var $auth_status = false; + + var $_is_user = false; + + var $_priviledge_level; + + var $_is_priviledged = false; + + var $params; + + var $check_for_credentials = false; + + /** + * Auth class Singleton + * + * @return owa_auth + */ + public static function get_instance($plugin = '') { + + static $auth; + + if (!$auth) { + + $auth = new owa_auth(); + + } + + return $auth; + } + + + /** + * Class Constructor + * + * @return owa_auth + */ + function __construct() { + + // register auth cookies + owa_coreAPI::registerStateStore('u', time()+3600*24*365*10, '', '', 'cookie'); + owa_coreAPI::registerStateStore('p', time()+3600*2, '', '', 'cookie'); + + parent::__construct(); + $this->eq = owa_coreAPI::getEventDispatch(); + } + + /** + * Used by controllers to check if the user exists and if they are priviledged. + * + * @param string $necessary_role + */ + function authenticateUser() { + + // check existing auth status first in case someone else took care of this already. + if (owa_coreAPI::getCurrentUser()->isAuthenticated()) { + $ret = true; + } elseif (owa_coreAPI::getRequestParam('apiKey')) { + // auth user by api key + $ret = $this->authByApiKey(owa_coreAPI::getRequestParam('apiKey')); + } elseif (owa_coreAPI::getRequestParam('pk') && owa_coreAPI::getStateParam('u')) { + // auth user by temporary passkey. used in forgot password situations + $ret = $this->authenticateUserByUrlPasskey(owa_coreAPI::getRequestParam('pk')); + } elseif (owa_coreAPI::getRequestParam('user_id') && owa_coreAPI::getRequestParam('password')) { + // auth user by login form input + $ret = $this->authByInput(owa_coreAPI::getRequestParam('user_id'), owa_coreAPI::getRequestParam('password')); + } elseif (owa_coreAPI::getStateParam('u') && owa_coreAPI::getStateParam('p')) { + // auth user by cookies + $ret = $this->authByCookies(owa_coreAPI::getStateParam('u'), owa_coreAPI::getStateParam('p')); + // bump expiration time + //owa_coreAPI::setState('p', '', owa_coreAPI::getStateParam('p')); + } else { + $ret = false; + owa_coreAPI::debug("Could not find any credentials to authenticate with."); + } + + // filter results for modules can add their own auth logic. + $ret = $this->eq->filter('auth_status', $ret); + + return array('auth_status' => $ret); + + } + + function authByApiKey( $key ) { + + $key = owa_sanitize::cleanMd5( $key ); + + if ( $key ) { + + // fetch user object from the db + $this->u = owa_coreAPI::entityFactory('base.user'); + $this->u->load($key, 'api_key'); + + if ($this->u->get('user_id')) { + // get current user + $cu = owa_coreAPI::getCurrentUser(); + // set as new current user in service layer + $cu->loadNewUserByObject($this->u); + $cu->setAuthStatus(true); + $this->_is_user = true; + return true; + } else { + return false; + } + + } else { + + return false; + } + + } + + function authByCookies($user_id, $password) { + + // set credentials + $this->credentials['user_id'] = owa_sanitize::cleanUserId( $user_id ); + $this->credentials['password'] = $password; + + // lookup user if not already done. + if ($this->_is_user == false) { + + // check to see if the current user has already been authenticated by something upstream + $cu = owa_coreAPI::getCurrentUser(); + if (!$cu->isAuthenticated()) { + // check to see if they are a user. + $val = $this->isUser(); + //print ("val: ". $val); + return $val; + } + } else { + return true; + } + } + + function authByInput($user_id, $password) { + + // set credentials + $this->credentials['user_id'] = owa_sanitize::cleanUserId( $user_id ); + // must encrypt password to see if it matches whats in the db + $this->credentials['password'] = $this->generateAuthCredential( $this->credentials['user_id'], $this->encryptOldPassword( $password ) ); + // pass plain text password to test with password_verify + $this->credentials['new_password'] = $password; + //owa_coreAPI::debug(print_r($this->credentials, true)); + $ret = $this->isUser(); + + if ($ret === true) { + $this->saveCredentials(); + } + + return $ret; + } + + /** + * Looks up user by temporary Passkey Column in db + * + * @param unknown_type $key + * @return unknown + */ + function authenticateUserTempPasskey( $key ) { + + $key = owa_sanitize::cleanMd5( $key ); + + if ( $key ) { + + $this->u = owa_coreAPI::entityFactory('base.user'); + $this->u->getByColumn('temp_passkey', $key); + + $id = $this->u->get('id'); + + if (!empty($id)) { + + return true; + + } else { + + return false; + } + + } else { + + return false; + } + } + + /** + * Authenticates user by a passkey + * + * @param unknown_type $key + * @return unknown + */ + function authenticateUserByUrlPasskey($user_id, $passkey) { + + $passkey = owa_sanitize::cleanMd5( $passkey ); + + if ( $passkey ) { + + // set credentials + $this->credentials['user_id'] = $user_id; + $this->credentials['passkey'] = $passkey; + + // fetch user obj + $this->getUser(); + + // generate a new passkey from its components in the db + $key = $this->generateUrlPasskey($this->u->get('user_id'), $this->u->get('password')); + + // see if it matches the key on the url + if ($key == $passkey) { + + return true; + + } else { + return false; + } + + } else { + + return false; + } + } + + /** + * Sets a temporary Passkey for a user + * + * @param string $email_address + * @return boolean + */ + function setTempPasskey($email_address) { + + $this->u = owa_coreAPI::entityFactory('base.user'); + $this->u->getByColumn('email_address', $email_address); + + $id = $u->get('id'); + + if (!empty($id)): + + $this->eq->log(array('email_address' => $this->u->email_address), 'user.set_temp_passkey'); + return true; + else: + return false; + endif; + + } + + function generateTempPasskey($seed) { + + return md5($seed.time().rand()); + } + + function generateUrlPasskey($user_name, $password) { + + return md5($user_name . $password); + + } + + /** + * Sets the initial Passkey for a new user + * + * @param string $user_id + * @return boolean + * @deprecated + */ + function setInitialPasskey($user_id) { + + return $this->eq->log(array('user_id' => $user_id), 'user.set_initial_passkey'); + + } + + /** + * Saves login credentails to persistant browser cookies + * TODO: refactor to use state facility + */ + function saveCredentials() { + + $this->e->debug('saving user credentials to cookies'); + + if (PHP_VERSION_ID < 70300) { + setcookie($this->config['ns'].'u', $this->u->get('user_id'), time()+3600*24*365*10, '/; samesite=None', $this->config['cookie_domain']); + setcookie($this->config['ns'].'p', $this->generateAuthCredential( $this->credentials['user_id'], $this->u->get('password') ), time()+3600*24*2, '/; samesite=None', $this->config['cookie_domain']); + } else { + setcookie($this->config['ns'].'u', $this->u->get('user_id'), [ + 'expires' => time()+3600*24*365*10, + 'path' => '/', + 'samesite' => 'None', + 'domain' => $this->config['cookie_domain'], + ]); + setcookie($this->config['ns'].'p', $this->generateAuthCredential( $this->credentials['user_id'], $this->u->get('password') ), [ + 'expires' => time()+3600*24*365*10, + 'path' => '/', + 'samesite' => 'None', + 'domain' => $this->config['cookie_domain'], + ]); + } + } + + /** + * Removes credentials + * @return boolean + */ + function deleteCredentials() { + + return owa_coreAPI::clearState('p'); + } + + /** + * Simple Password Encryption Scheme + * + * @param string $password + * @return string + */ + function encryptPassword($password) { + + return owa_lib::encryptPassword($password); + + } + function encryptOldPassword($password) { + + return owa_lib::encryptOldPassword($password); + + } + + function getUser() { + + // fetch user object from the db + $this->u = owa_coreAPI::entityFactory('base.user'); + $this->u->getByColumn('user_id', $this->credentials['user_id']); + } + + /** + * Checks to see if the user credentials match a real user object in the DB + * + * @return boolean + */ + function isUser() { + + // get current user + $cu = owa_coreAPI::getCurrentUser(); + + // fetches user object from DB + $this->getUser(); + + if ( $this->credentials['user_id'] === $this->u->get('user_id') ) { + + // new_password will only be set when using authByInput + if ( isset($this->credentials['new_password']) ) { + // plain text password matches DB password we can authorize + if ( password_verify( $this->credentials['new_password'], $this->u->get('password') ) ) { + $this->_is_user = true; + + // set as new current user in service layer + $cu->loadNewUserByObject( $this->u ); + $cu->setAuthStatus(true); + + return true; + } + } + + //if ($this->credentials['password'] === $this->u->get('password')): + if ( $this->isValidAuthCredential( $this->credentials['user_id'], $this->credentials['password'] ) ) { + $this->_is_user = true; + + // set as new current user in service layer + $cu->loadNewUserByObject( $this->u ); + $cu->setAuthStatus(true); + + return true; + } else { + $this->_is_user = false; + return false; + } + } else { + $this->_is_user = false; + return false; + } + } + + function isValidAuthCredential( $user_id, $passed_credential ) { + + $hash = ''; + $hash = $this->reconstructAuthCredential( $user_id ); + //print "hash: $hash "; + //print "passed credential: $passed_credential "; + if ( function_exists('hash_equals') ) { + + return hash_equals( $hash, $passed_credential ); + + } else { + + if ( $hash === $passed_credential ) { + + return true; + } + } + } + + function reconstructAuthCredential( $user_id ) { + + $u = owa_coreAPI::entityFactory('base.user'); + + $u->getByColumn( 'user_id', $user_id ); + + $password = $u->get('password'); + //print "password $password"; + return $this->generateAuthCredential( $user_id, $password ); + } + + function generateAuthCredential($user_id, $password, $expiration = '', $scheme = 'auth') { + + $frag = substr($password, 8, 4); + + $key = owa_coreAPI::saltedHash( $user_id . $frag . $expiration, $scheme ); + + $algo = 'sha1'; + + if ( function_exists( 'hash' ) ) { + + $algo = 'sha256'; + + } + + $hash = owa_lib::hash( $algo, $user_id . $expiration, $key ); + + $credential = $hash; // could add other elements here. + + return $credential; + } + +} + +?> diff --git a/owa_base.php b/owa_base.php index 4bfc06b2a..eb2f874e9 100644 --- a/owa_base.php +++ b/owa_base.php @@ -26,58 +26,58 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_base { - - /** - * Configuration - * - * @var array - */ - var $config; - - /** - * Error Logger - * - * @var object - */ - var $e; - - /** - * Configuration Entity - * - * @var owa_settings Object global configuration object - */ - var $c; - - /** - * Module that this class belongs to - * - * @var unknown_type - */ - var $module; - - /** - * Request Params - * - * @var array - */ - var $params; - - /** - * Base Constructor - * - * @return owa_base - */ - function __construct() { - owa_coreAPI::profile($this, __FUNCTION__, __LINE__); - $this->e = owa_coreAPI::errorSingleton(); - $this->c = owa_coreAPI::configSingleton(); - $this->config = $this->c->fetch('base'); - } + + /** + * Configuration + * + * @var array + */ + var $config; + + /** + * Error Logger + * + * @var object + */ + var $e; + + /** + * Configuration Entity + * + * @var owa_settings Object global configuration object + */ + var $c; + + /** + * Module that this class belongs to + * + * @var unknown_type + */ + var $module; + + /** + * Request Params + * + * @var array + */ + var $params; + + /** + * Base Constructor + * + * @return owa_base + */ + function __construct() { + owa_coreAPI::profile($this, __FUNCTION__, __LINE__); + $this->e = owa_coreAPI::errorSingleton(); + $this->c = owa_coreAPI::configSingleton(); + $this->config = $this->c->fetch('base'); + } /** * Retrieves string message from mesage file @@ -86,31 +86,31 @@ function __construct() { * @param array $substitutions * @return array */ - function getMsg($code, $substitutions = []) { - - static $_owa_messages; - - $msg = array(); - - if (empty($_owa_messages)) { - require_once(OWA_DIR.'conf/messages.php'); - } - - if ( $code && array_key_exists( $code, $_owa_messages ) ) { - - $msg = $_owa_messages[$code]; - - if (isset($msg['headline'])) { - $msg['headline'] = vsprintf($msg['headline'], $substitutions['headline']); - } - - if (isset($msg['message'])) { - $msg['message'] = vsprintf($msg['message'], $substitutions['message']); - } - } - - return $msg; - } + function getMsg($code, $substitutions = []) { + + static $_owa_messages; + + $msg = array(); + + if (empty($_owa_messages)) { + require_once(OWA_DIR.'conf/messages.php'); + } + + if ( $code && array_key_exists( $code, $_owa_messages ) ) { + + $msg = $_owa_messages[$code]; + + if (isset($msg['headline'])) { + $msg['headline'] = vsprintf($msg['headline'], $substitutions['headline']); + } + + if (isset($msg['message'])) { + $msg['message'] = vsprintf($msg['message'], $substitutions['message']); + } + } + + return $msg; + } /** * @param $code @@ -122,44 +122,44 @@ public function getMsgAsString($code, $substitutions = []) $msg = $this->getMsg($code, $substitutions); return implode(' ', array_values($msg)); - } - - /** - * Sets object attributes - * - * @param unknown_type $array - */ - function _setObjectValues($array) { - - foreach ($array as $n => $v) { - - $this->$n = $v; - - } - - return; - } - - /** - * Sets array attributes - * - * @param unknown_type $array - */ - function _setArrayValues($array) { - - foreach ($array as $n => $v) { - - $this->params['$n'] = $v; - - } - - return; - } - - function __destruct() { - owa_coreAPI::profile($this, __FUNCTION__, __LINE__); - } - + } + + /** + * Sets object attributes + * + * @param unknown_type $array + */ + function _setObjectValues($array) { + + foreach ($array as $n => $v) { + + $this->$n = $v; + + } + + return; + } + + /** + * Sets array attributes + * + * @param unknown_type $array + */ + function _setArrayValues($array) { + + foreach ($array as $n => $v) { + + $this->params['$n'] = $v; + + } + + return; + } + + function __destruct() { + owa_coreAPI::profile($this, __FUNCTION__, __LINE__); + } + } ?> \ No newline at end of file diff --git a/owa_caller.php b/owa_caller.php index 0fd77f6ef..2c854765b 100644 --- a/owa_caller.php +++ b/owa_caller.php @@ -1,333 +1,333 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_caller extends owa_base { - - /** - * Request Params from get or post - * - * @var array - */ - var $params; - - var $start_time; - - var $end_time; - - var $update_required; - - var $service; - - var $site_id; - - /** - * Constructor - * - * @param array $config - * @return owa_caller - */ - function __construct($config = array()) { - - if (empty($config)) { - $config = array(); - } - - // Start time - $this->start_time = owa_lib::microtime_float(); - - /* SETUP CONFIGURATION AND ERROR LOGGER */ - - // Parent Constructor. Sets default config entity and error logger - parent::__construct(); - - // Log version debug - $this->e->debug(sprintf('*** Starting Open Web Analytics v%s. Running under PHP v%s (%s) ***', OWA_VERSION, PHP_VERSION, PHP_OS)); - if ( array_key_exists('REQUEST_URI', $_SERVER ) ) { - owa_coreAPI::debug( 'Request URL: '.$_SERVER['REQUEST_URI'] ); - } - - if ( array_key_exists('HTTP_USER_AGENT', $_SERVER ) ) { - owa_coreAPI::debug( 'User Agent: '.$_SERVER['HTTP_USER_AGENT'] ); - } - - if ( array_key_exists('HTTP_HOST', $_SERVER ) ) { - owa_coreAPI::debug( 'Host: '.$_SERVER['HTTP_HOST'] ); - } - //owa_coreAPI::debug('cookie domain in caller: '. owa_coreAPI::getSetting('base', 'cookie_domain')); - // Backtrace. handy for debugging who called OWA - //$bt = debug_backtrace(); - //$this->e->debug($bt[4]); - - // load config values from DB - // Applies config from db or cache - // check here is needed for installs when the configuration table does not exist. - - if (!defined('OWA_INSTALLING')) { - if ($this->c->get('base', 'do_not_fetch_config_from_db') != true) { - if ($this->c->isConfigFilePresent()) { - $this->c->load( $this->c->get( 'base', 'configuration_id' ) ); - } - } - } - - // set timezone once config is loaded from DB. - $this->c->setTimezone(); - - - /* APPLY CALLER CONFIGURATION OVERRIDES */ - - // overrides all default and user config values except defined in the config file - // must come after user overides are applied - // This will apply configuration overirdes that are specified by the calling application. - // This is usually used by plugins to setup integration specific configuration values. - - $this->c->applyModuleOverrides('base', $config); - - $this->e->debug('Caller configuration overrides applied.'); - - /* SET ERROR HANDLER */ - - // Sets the correct mode of the error logger now that final config values are in place - // This will flush buffered msgs that were thrown up untill this point - $this->e->setHandler($this->c->get('base', 'error_handler')); - - /* PHP ERROR LOGGING */ - - /* - if (defined('OWA_LOG_PHP_ERRORS')) { - - $this->e->logPhpErrors(); - } - - set_exception_handler( array($this->e, 'logException') ); - */ - - /* LOAD SERVICE LAYER */ - $this->service = owa_coreAPI::serviceSingleton(); - // initialize framework - $this->service->initializeFramework(); - // notify handlers of 'init' action - $dispatch = owa_coreAPI::getEventDispatch(); - $dispatch->notify($dispatch->makeEvent('init')); - - /* SET SITE ID */ - // needed in standalone installs where site_id is not set in config file. - // still needed?????? - if (!empty($this->params['site_id'])) { - $this->c->set('base', 'site_id', $this->params['site_id']); - } - - // re-fetch the array now that overrides have been applied. - // needed for backwards compatability - $this->config = $this->c->fetch('base'); - - /* SETUP REQUEST Params */ - // still needed????? - $this->params = $this->service->request->getAllOwaParams(); - } - - function handleRequestFromUrl() { - - //$this->params = owa_lib::getRequestParams(); - return $this->handleRequest(); - - } - - - /** - * Returns a configured javascript tracker for inclusion in your web page. - * You can pass an options array to control what the tracker will log. - * The options array is a key/value pair format like: - * - * $options = array('do_not_log_pageview' => true); - * - * Option keys include: 'do_not_log_pageview', 'do_not_log_clicks', 'do_not_log_domstream' - * - * @param $echo bool if true the function will echo. if false the tracker is returned asa string. - * @param $options array an key value pair option array - * @return $tag string the tracker javascript. - */ - function placeHelperPageTags($echo = true, $options = array()) { - - if( ! owa_coreAPI::getRequestParam( 'is_robot' ) ) { - - if ( ! class_exists( 'owa_template' ) ) { - - require_once(OWA_BASE_CLASSES_DIR.'owa_template.php'); - } - - $t = new owa_template(); - $t->set_template('js_helper_tags.tpl'); - - $tracking_code = owa_coreAPI::getJsTrackerTag( $this->getSiteId(), $options ); - $t->set('tracking_code', $tracking_code); - $tag = $t->fetch(); - - if ($echo == false) { - return $tag; - } else { - echo $tag; - } - } - } - - // needed? - function handleHelperPageTagsRequest() { - - $params = array(); - $params['do'] = 'base.helperPageTags'; - return $this->handleRequest($params); - - } - - /** - * Handles OWA internal page/action requests - * - * @return unknown - */ - function handleRequest($caller_params = null, $action = '') { - - return owa_coreAPI::handleRequest($caller_params, $action); - - } - - function handleSpecialActionRequest() { - - if(isset($_GET['owa_specialAction'])): - $this->e->debug("special action received"); - echo $this->handleRequestFromUrl(); - $this->e->debug("special action complete"); - exit; - elseif(isset($_GET['owa_logAction'])): - $this->e->debug("log action received"); - $this->config['delay_first_hit'] = false; - $this->c->set('base', 'delay_first_hit', false); - echo $this->logEventFromUrl(); - exit; - elseif(isset($_GET['owa_apiAction'])): - $this->e->debug("api action received"); - define('OWA_API', true); - // lookup method class - echo $this->handleRequest('', 'base.apiRequest'); - exit; - else: - owa_coreAPI::debug('hello from special action request method in caller. no action to do.'); - return; - endif; - - } - - function __destruct() { - - $this->end_time = owa_lib::microtime_float(); - $total_time = $this->end_time - $this->start_time; - $this->e->debug(sprintf('Total session time: %s',$total_time)); - $this->e->debug("goodbye from OWA"); - owa_coreAPI::profileDisplay(); - - return; - } - - function setSetting($module, $name, $value) { - - return owa_coreAPI::setSetting($module, $name, $value); - } - - function getSetting($module, $name) { - - return owa_coreAPI::getSetting($module, $name); - } - - function setCurrentUser($role, $login_name = '') { - $cu = owa_coreAPI::getCurrentUser(); - $cu->setRole($role); - $cu->setAuthStatus(true); - } - - function makeEvent($type = '') { - - $event = owa_coreAPI::supportClassFactory('base', 'event'); - - if ($type) { - $event->setEventType($type); - } - - return $event; - } - - function setSiteId($site_id) { - - $this->site_id = $site_id; - } - - function getSiteId() { - - return $this->site_id; - } - - function setErrorHandler($mode) { - $this->e->setHandler($mode); - } - - function isOwaInstalled() { - - $version = owa_coreAPI::getSetting('base', 'schema_version'); - - if ($version > 0) { - return true; - } else { - return false; - } - } - - function isEndpointEnabled($file_name) { - - if ( ! $this->getSetting('base', 'disableAllEndpoints') ) { - $disabled_endpoints = $this->getSetting('base', 'disabledEndpoints'); - - if ( ! in_array( $file_name, $disabled_endpoints ) ) { - return true; - } - } - } - - function restInPeace() { - - return false; - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_caller extends owa_base { + + /** + * Request Params from get or post + * + * @var array + */ + var $params; + + var $start_time; + + var $end_time; + + var $update_required; + + var $service; + + var $site_id; + + /** + * Constructor + * + * @param array $config + * @return owa_caller + */ + function __construct($config = array()) { + + if (empty($config)) { + $config = array(); + } + + // Start time + $this->start_time = owa_lib::microtime_float(); + + /* SETUP CONFIGURATION AND ERROR LOGGER */ + + // Parent Constructor. Sets default config entity and error logger + parent::__construct(); + + // Log version debug + $this->e->debug(sprintf('*** Starting Open Web Analytics v%s. Running under PHP v%s (%s) ***', OWA_VERSION, PHP_VERSION, PHP_OS)); + if ( array_key_exists('REQUEST_URI', $_SERVER ) ) { + owa_coreAPI::debug( 'Request URL: '.$_SERVER['REQUEST_URI'] ); + } + + if ( array_key_exists('HTTP_USER_AGENT', $_SERVER ) ) { + owa_coreAPI::debug( 'User Agent: '.$_SERVER['HTTP_USER_AGENT'] ); + } + + if ( array_key_exists('HTTP_HOST', $_SERVER ) ) { + owa_coreAPI::debug( 'Host: '.$_SERVER['HTTP_HOST'] ); + } + //owa_coreAPI::debug('cookie domain in caller: '. owa_coreAPI::getSetting('base', 'cookie_domain')); + // Backtrace. handy for debugging who called OWA + //$bt = debug_backtrace(); + //$this->e->debug($bt[4]); + + // load config values from DB + // Applies config from db or cache + // check here is needed for installs when the configuration table does not exist. + + if (!defined('OWA_INSTALLING')) { + if ($this->c->get('base', 'do_not_fetch_config_from_db') != true) { + if ($this->c->isConfigFilePresent()) { + $this->c->load( $this->c->get( 'base', 'configuration_id' ) ); + } + } + } + + // set timezone once config is loaded from DB. + $this->c->setTimezone(); + + + /* APPLY CALLER CONFIGURATION OVERRIDES */ + + // overrides all default and user config values except defined in the config file + // must come after user overides are applied + // This will apply configuration overirdes that are specified by the calling application. + // This is usually used by plugins to setup integration specific configuration values. + + $this->c->applyModuleOverrides('base', $config); + + $this->e->debug('Caller configuration overrides applied.'); + + /* SET ERROR HANDLER */ + + // Sets the correct mode of the error logger now that final config values are in place + // This will flush buffered msgs that were thrown up untill this point + $this->e->setHandler($this->c->get('base', 'error_handler')); + + /* PHP ERROR LOGGING */ + + /* + if (defined('OWA_LOG_PHP_ERRORS')) { + + $this->e->logPhpErrors(); + } + + set_exception_handler( array($this->e, 'logException') ); + */ + + /* LOAD SERVICE LAYER */ + $this->service = owa_coreAPI::serviceSingleton(); + // initialize framework + $this->service->initializeFramework(); + // notify handlers of 'init' action + $dispatch = owa_coreAPI::getEventDispatch(); + $dispatch->notify($dispatch->makeEvent('init')); + + /* SET SITE ID */ + // needed in standalone installs where site_id is not set in config file. + // still needed?????? + if (!empty($this->params['site_id'])) { + $this->c->set('base', 'site_id', $this->params['site_id']); + } + + // re-fetch the array now that overrides have been applied. + // needed for backwards compatability + $this->config = $this->c->fetch('base'); + + /* SETUP REQUEST Params */ + // still needed????? + $this->params = $this->service->request->getAllOwaParams(); + } + + function handleRequestFromUrl() { + + //$this->params = owa_lib::getRequestParams(); + return $this->handleRequest(); + + } + + + /** + * Returns a configured javascript tracker for inclusion in your web page. + * You can pass an options array to control what the tracker will log. + * The options array is a key/value pair format like: + * + * $options = array('do_not_log_pageview' => true); + * + * Option keys include: 'do_not_log_pageview', 'do_not_log_clicks', 'do_not_log_domstream' + * + * @param $echo bool if true the function will echo. if false the tracker is returned asa string. + * @param $options array an key value pair option array + * @return $tag string the tracker javascript. + */ + function placeHelperPageTags($echo = true, $options = array()) { + + if( ! owa_coreAPI::getRequestParam( 'is_robot' ) ) { + + if ( ! class_exists( 'owa_template' ) ) { + + require_once(OWA_BASE_CLASSES_DIR.'owa_template.php'); + } + + $t = new owa_template(); + $t->set_template('js_helper_tags.tpl'); + + $tracking_code = owa_coreAPI::getJsTrackerTag( $this->getSiteId(), $options ); + $t->set('tracking_code', $tracking_code); + $tag = $t->fetch(); + + if ($echo == false) { + return $tag; + } else { + echo $tag; + } + } + } + + // needed? + function handleHelperPageTagsRequest() { + + $params = array(); + $params['do'] = 'base.helperPageTags'; + return $this->handleRequest($params); + + } + + /** + * Handles OWA internal page/action requests + * + * @return unknown + */ + function handleRequest($caller_params = null, $action = '') { + + return owa_coreAPI::handleRequest($caller_params, $action); + + } + + function handleSpecialActionRequest() { + + if(isset($_GET['owa_specialAction'])): + $this->e->debug("special action received"); + echo $this->handleRequestFromUrl(); + $this->e->debug("special action complete"); + exit; + elseif(isset($_GET['owa_logAction'])): + $this->e->debug("log action received"); + $this->config['delay_first_hit'] = false; + $this->c->set('base', 'delay_first_hit', false); + echo $this->logEventFromUrl(); + exit; + elseif(isset($_GET['owa_apiAction'])): + $this->e->debug("api action received"); + define('OWA_API', true); + // lookup method class + echo $this->handleRequest('', 'base.apiRequest'); + exit; + else: + owa_coreAPI::debug('hello from special action request method in caller. no action to do.'); + return; + endif; + + } + + function __destruct() { + + $this->end_time = owa_lib::microtime_float(); + $total_time = $this->end_time - $this->start_time; + $this->e->debug(sprintf('Total session time: %s',$total_time)); + $this->e->debug("goodbye from OWA"); + owa_coreAPI::profileDisplay(); + + return; + } + + function setSetting($module, $name, $value) { + + return owa_coreAPI::setSetting($module, $name, $value); + } + + function getSetting($module, $name) { + + return owa_coreAPI::getSetting($module, $name); + } + + function setCurrentUser($role, $login_name = '') { + $cu = owa_coreAPI::getCurrentUser(); + $cu->setRole($role); + $cu->setAuthStatus(true); + } + + function makeEvent($type = '') { + + $event = owa_coreAPI::supportClassFactory('base', 'event'); + + if ($type) { + $event->setEventType($type); + } + + return $event; + } + + function setSiteId($site_id) { + + $this->site_id = $site_id; + } + + function getSiteId() { + + return $this->site_id; + } + + function setErrorHandler($mode) { + $this->e->setHandler($mode); + } + + function isOwaInstalled() { + + $version = owa_coreAPI::getSetting('base', 'schema_version'); + + if ($version > 0) { + return true; + } else { + return false; + } + } + + function isEndpointEnabled($file_name) { + + if ( ! $this->getSetting('base', 'disableAllEndpoints') ) { + $disabled_endpoints = $this->getSetting('base', 'disabledEndpoints'); + + if ( ! in_array( $file_name, $disabled_endpoints ) ) { + return true; + } + } + } + + function restInPeace() { + + return false; + } + +} + ?> \ No newline at end of file diff --git a/owa_controller.php b/owa_controller.php index 793903f25..3ed8a58db 100644 --- a/owa_controller.php +++ b/owa_controller.php @@ -1,618 +1,618 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_controller extends owa_base { - - /** - * Request Parameters passed in from caller - * - * @var array - */ - var $params = array(); - - /** - * Controller Type - * - * @var array - */ - var $type; - - /** - * Is the controller for an admin function - * - * @var boolean - */ - var $is_admin; - - /** - * The priviledge level required to access this controller - * - * @var string - */ - var $priviledge_level; - - /** - * data validation control object - * - * @var Object - */ - var $v; - - /** - * Data container - * - * @var Array - */ - var $data = array(); - - /** - * Capability - * - * @var string - */ - var $capability; - - /** - * Available Views - * - * @var Array - */ - var $available_views = array(); - - /** - * Time period - * - * @var Object - */ - var $period; - - /** - * Dom id - * - * @var String - */ - var $dom_id; - - /** - * Flag for requiring authenciation before performing actions - * - * @var Bool - */ - var $authenticate_user; - - var $state; - - /** - * Flag for requiring nonce before performing write actions - * - * @var Bool - */ - var $is_nonce_required = false; - - /** - * Constructor - * - * @param array $params - */ - function __construct($params) { - - // call parent constructor to setup objects. - parent::__construct(); - - // set request params - $this->params = $params; - - // set the default view method - $this->setViewMethod('delegate'); - } - - /** - * Handles request from caller - * - */ - function doAction() { - - owa_coreAPI::debug('Performing Action: '.get_class($this)); - - // check if the schema needs to be updated and force the update - // not sure this should go here... - if ($this->is_admin === true) { - // do not intercept if its the updatesApply action or a re-install else updates will never apply - $do = $this->getParam('do'); - if ($do != 'base.updatesApply' && !defined('OWA_INSTALLING') && !defined('OWA_UPDATING')) { - - if (owa_coreAPI::isUpdateRequired()) { - $this->e->debug('Updates Required. Redirecting action.'); - $data = array(); - $data['view_method'] = 'redirect'; - $data['action'] = 'base.updates'; - return $data; - } - } - } - - - - - - /* CHECK USER FOR CAPABILITIES */ - if (!$this->checkCapabilityAndAuthenticateUser($this->getRequiredCapability())) { - return $this->data; - } - - /* Check validity of nonce */ - if ($this->is_nonce_required == true) { - $nonce = $this->getParam('nonce'); - - if (!$nonce || !$this->verifyNonce($nonce)) { - $this->e->debug('Nonce is not valid.'); - return $this->finishActionCall($this->notAuthenticatedAction()); - } - } - - // TODO: These sets need to be removed and added to pre(), action() or post() methods - // in various concrete controller classes as they screw up things when - // redirecting from one controller to another. - - // set auth status for downstream views - //$this->set('auth_status', true); - //set request params - $this->set('params', $this->params); - // set site_id - $this->set('site_id', $this->get('site_id')); - - // set status msg - NEEDED HERE? doesnt owa_ view handle this? - if (array_key_exists('status_code', $this->params)) { - $this->set('status_code', $this->getParam('status_code')); - } - - // get error msg from error code passed on the query string from a redirect. - if (array_key_exists('error_code', $this->params)) { - $this->set('error_code', $this->getParam('error_code')); - } - - // check to see if the controller has created a validator - if (!empty($this->v)) { - // if so do the validations required - $this->v->doValidations(); - //check for errors - if ($this->v->hasErrors === true) { - //print_r($this->v); - // if errors, do the errorAction instead of the normal action - $this->set('validation_errors', $this->getValidationErrorMsgs()); - return $this->finishActionCall($this->errorAction()); - } - } - - /* PERFORM PRE ACTION */ - // often used by abstract descendant controllers to set various things - $this->pre(); - /* PERFORM MAIN ACTION */ - return $this->finishActionCall($this->action()); - } - - /** - * Checks for the action result, calls the post method and returns correct result - * Usage return $this->finishActionCall($this->action())) - * @return mixed - */ - protected function finishActionCall($actionResult) { - // need to check ret for backwards compatability with older - // controllers that donot use $this->data - if (!empty($actionResult)) { - $this->post(); - return $actionResult; - } else { - $this->post(); - return $this->data; - } - } - - /** - * Checks if the current controller requires privileges and authenticates the user and checks for capabilities - * If the user is not allowed the correct error view is also initialized and the calling method should return - * @uses ->getRequiredCapability and ->getCurrentSiteId - * @param string $capability - * @return boolean - */ - protected function checkCapabilityAndAuthenticateUser($capability) { - if ( !empty($capability) && ! owa_coreAPI::isEveryoneCapable( $capability ) ) { - /* PERFORM AUTHENTICATION */ - $auth = owa_auth::get_instance(); - if (!owa_coreAPI::isCurrentUserAuthenticated()) { - $status = $auth->authenticateUser(); - if ($status['auth_status'] != true) { - $this->notAuthenticatedAction(); - return false; - } - } - - $currentUser = owa_coreAPI::getCurrentUser(); - if (!$currentUser->isCapable($this->getRequiredCapability(),$this->getCurrentSiteId())) { - owa_coreAPI::debug('User does not have capability required by this controller.'); - $this->authenticatedButNotCapableAction(); - //needed? - //$this->set('go', urlencode(owa_lib::get_current_url())); - // needed? -- set auth status for downstream views - //$this->set('auth_status', true); - return false; - } - - } - return true; - } - - // needed? - protected function isEveryoneCapable($capability) { - - return owa_coreAPI::isEveryoneCapable( $capability ); - } - - function logEvent($event_type, $properties) { - - $ed = owa_coreAPI::getEventDispatch(); - - if (!is_a($properties, 'owa_event')) { - - $event = owa_coreAPI::supportClassFactory('base', 'event'); - $event->setProperties($properties); - $event->setEventType($event_type); - } else { - $event = $properties; - } - - return $ed->notify( $event ); - } - - function createValidator() { - - $this->v = owa_coreAPI::supportClassFactory('base', 'validator'); - } - - function addValidation($name, $value, $validation, $conf = array()) { - - if ( empty( $this->v ) ) { - - $this->createValidator(); - } - - return $this->v->addValidation($name, $value, $validation, $conf); - - } - - function setValidation($name, $obj) { - - if (empty($this->v)) { - $this->createValidator(); - } - - return $this->v->setValidation($name, $obj); - } - - function getValidationErrorMsgs() { - - return $this->v->getErrorMsgs(); - - } - - function isAdmin() { - - if ($this->is_admin == true) { - return true; - } - } - - // depricated - function _setCapability($capability) { - - $this->setRequiredCapability($capability); - } - - function setRequiredCapability($capability) { - - $this->capability = $capability; - } - - function getRequiredCapability() { - - return $this->capability; - } - - function getParam($name) { - - if (array_key_exists($name, $this->params)) { - return $this->params[$name]; - } - } - - function setParam($name, $value) { - - $this->params[$name] = $value; - } - - function isParam($name) { - - if (array_key_exists($name, $this->params)) { - return true; - } - } - - function get($name) { - - return $this->getParam($name); - } - - function getAllParams() { - - return $this->params; - } - - function pre() { - - return false; - } - - function post() { - return false; - } - - function getPeriod() { - - return $this->period; - } - - function setPeriod() { - // set period - - $period = $this->makeTimePeriod($this->getParam('period'), $this->params); - - $this->period = $period; - $this->set('period', $this->getPeriod()); - $this->data['params'] = array_merge($this->data['params'], $period->getPeriodProperties()); - } - - function makeTimePeriod($time_period, $params = array()) { - - return owa_coreAPI::makeTimePeriod($time_period, $params); - } - - function setTimePeriod($period) { - - $this->period = $period; - $this->set('period', $this->getPeriod()); - //$this->data['params'] = array_merge($this->data['params'], $period->getPeriodProperties()); - } - - - function setView($view) { - - $this->data['view'] = $view; - } - - function setSubview($subview) { - - $this->data['subview'] = $subview; - - } - - function setViewMethod($method = 'delegate') { - - $this->data['view_method'] = $method; - - } - - function setRedirectAction($do) { - - $this->set('view_method', 'redirect'); - $this->set('do', $do); - - // need to remove these unsets once they are no longer set in the main doAction method - if (array_key_exists('params', $this->data)) { - unset($this->data['params']); - } - if (array_key_exists('site_id', $this->data)) { - // unset($this->data['site_id']); - } - } - - function setPagination($pagination, $name = 'pagination') { - - $this->data[$name] = $pagination; - - } - - function set($name, $value) { - - $this->data[$name] = $value; - } - - function setControllerType($string) { - - $this->type = $string; - - } - - function mergeParams($array) { - - $this->params = array_merge($this->params, $array); - - } - - /** - * redirects borwser to a particular view - * - * @param unknown_type $data - */ - function redirectBrowser($action, $pass_params = true) { - - $control_params = array('view_method', 'auth_status'); - - $get = ''; - - $get .= owa_coreAPI::getSetting('base', 'ns').'do'.'='.$action.'&'; - - if ($pass_params === true) { - - foreach ($this->data as $n => $v) { - - if (!in_array($n, $control_params)) { - - $get .= owa_coreAPI::getSetting('base', 'ns').$n.'='.$v.'&'; - - } - } - } - - $new_url = sprintf(owa_coreAPI::getSetting('base', 'link_template'), owa_coreAPI::getSetting('base', 'main_url'), $get); - - return owa_lib::redirectBrowser($new_url); - - } - - function redirectBrowserToUrl($url) { - - return owa_lib::redirectBrowser($url); - } - - function setStatusCode($code) { - - $this->data['status_code'] = $code; - } - - function setStatusMsg($msg) { - - $this->data['status_message'] = $msg; - } - - function setErrorMsg( $msg ) { - - $this->set( 'error_msg', $msg ); - } - - function authenticatedButNotCapableAction($additionalMessage = '') { - if ( empty($additionalMessage) ) { - $siteIdMsg = $this->getCurrentSiteId(); - if ( empty ($siteIdMsg) ) { - $siteIdMsg = 'No access to any site for the permission "'.$this->getRequiredCapability().'"'; - } - $additionalMessage = $siteIdMsg; - } - $this->setView('base.error'); - $this->set('error_msg', $this->getMsg(2003).' '.$additionalMessage); - } - - function notAuthenticatedAction() { - - $this->setRedirectAction('base.loginForm'); - $this->set('go', urlencode(owa_lib::get_current_url())); - } - - function verifyNonce($nonce) { - - $action = $this->getParam('do'); - - if (!$action) { - $action = $this->getParam('action'); - } - - $matching_nonce = owa_coreAPI::createNonce($action); - owa_coreAPI::debug("passed nonce: $nonce | matching nonce: $matching_nonce"); - if ($nonce === $matching_nonce) { - return true; - } - } - - /** - * Sets nonce flag for the controller. - */ - function setNonceRequired() { - - $this->is_nonce_required = true; - } - - function getSetting($module, $name) { - return owa_coreAPI::getSetting($module, $name); - } - - - /** - * Returns array of owa_site entities where the current user has access to, taken the current controller cap into account - * @return array - */ - protected function getSitesAllowedForCurrentUser() { - owa_coreAPI::debug('get Sites Allowed for user'); - $currentUser = owa_coreAPI::getCurrentUser(); - - if ( $currentUser->isAnonymousUser() || $currentUser->isAdmin() ) { - $result = array(); - $relations = owa_coreAPI::getSitesList(); - - foreach ($relations as $siteRow) { - - $site = owa_coreAPI::entityFactory('base.site'); - $site->load($siteRow['id']); - $result[$siteRow['site_id']] = $site; - } - - return $result; - - } else { - return $currentUser->getAssignedSites(); - } - } - - /** - * gets the siteid taking the site access permissions into account - * If not a typical siteId parameter is set or user lacks permission, the first availabe site is used - * - * @return string or false if no site access - */ - protected function getCurrentSiteId() { - - $siteParameterValue = $this->getSiteIdParameterValue(); - return $siteParameterValue; - } - - /** - * @return integer or false - */ - protected function getSiteIdParameterValue() { - if ($this->getParam('siteId') ) { - return $this->getParam('siteId'); - } - elseif ($this->getParam('site_id') ) { - return $this->getParam('site_id'); - } - return false; - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_controller extends owa_base { + + /** + * Request Parameters passed in from caller + * + * @var array + */ + var $params = array(); + + /** + * Controller Type + * + * @var array + */ + var $type; + + /** + * Is the controller for an admin function + * + * @var boolean + */ + var $is_admin; + + /** + * The priviledge level required to access this controller + * + * @var string + */ + var $priviledge_level; + + /** + * data validation control object + * + * @var Object + */ + var $v; + + /** + * Data container + * + * @var Array + */ + var $data = array(); + + /** + * Capability + * + * @var string + */ + var $capability; + + /** + * Available Views + * + * @var Array + */ + var $available_views = array(); + + /** + * Time period + * + * @var Object + */ + var $period; + + /** + * Dom id + * + * @var String + */ + var $dom_id; + + /** + * Flag for requiring authenciation before performing actions + * + * @var Bool + */ + var $authenticate_user; + + var $state; + + /** + * Flag for requiring nonce before performing write actions + * + * @var Bool + */ + var $is_nonce_required = false; + + /** + * Constructor + * + * @param array $params + */ + function __construct($params) { + + // call parent constructor to setup objects. + parent::__construct(); + + // set request params + $this->params = $params; + + // set the default view method + $this->setViewMethod('delegate'); + } + + /** + * Handles request from caller + * + */ + function doAction() { + + owa_coreAPI::debug('Performing Action: '.get_class($this)); + + // check if the schema needs to be updated and force the update + // not sure this should go here... + if ($this->is_admin === true) { + // do not intercept if its the updatesApply action or a re-install else updates will never apply + $do = $this->getParam('do'); + if ($do != 'base.updatesApply' && !defined('OWA_INSTALLING') && !defined('OWA_UPDATING')) { + + if (owa_coreAPI::isUpdateRequired()) { + $this->e->debug('Updates Required. Redirecting action.'); + $data = array(); + $data['view_method'] = 'redirect'; + $data['action'] = 'base.updates'; + return $data; + } + } + } + + + + + + /* CHECK USER FOR CAPABILITIES */ + if (!$this->checkCapabilityAndAuthenticateUser($this->getRequiredCapability())) { + return $this->data; + } + + /* Check validity of nonce */ + if ($this->is_nonce_required == true) { + $nonce = $this->getParam('nonce'); + + if (!$nonce || !$this->verifyNonce($nonce)) { + $this->e->debug('Nonce is not valid.'); + return $this->finishActionCall($this->notAuthenticatedAction()); + } + } + + // TODO: These sets need to be removed and added to pre(), action() or post() methods + // in various concrete controller classes as they screw up things when + // redirecting from one controller to another. + + // set auth status for downstream views + //$this->set('auth_status', true); + //set request params + $this->set('params', $this->params); + // set site_id + $this->set('site_id', $this->get('site_id')); + + // set status msg - NEEDED HERE? doesnt owa_ view handle this? + if (array_key_exists('status_code', $this->params)) { + $this->set('status_code', $this->getParam('status_code')); + } + + // get error msg from error code passed on the query string from a redirect. + if (array_key_exists('error_code', $this->params)) { + $this->set('error_code', $this->getParam('error_code')); + } + + // check to see if the controller has created a validator + if (!empty($this->v)) { + // if so do the validations required + $this->v->doValidations(); + //check for errors + if ($this->v->hasErrors === true) { + //print_r($this->v); + // if errors, do the errorAction instead of the normal action + $this->set('validation_errors', $this->getValidationErrorMsgs()); + return $this->finishActionCall($this->errorAction()); + } + } + + /* PERFORM PRE ACTION */ + // often used by abstract descendant controllers to set various things + $this->pre(); + /* PERFORM MAIN ACTION */ + return $this->finishActionCall($this->action()); + } + + /** + * Checks for the action result, calls the post method and returns correct result + * Usage return $this->finishActionCall($this->action())) + * @return mixed + */ + protected function finishActionCall($actionResult) { + // need to check ret for backwards compatability with older + // controllers that donot use $this->data + if (!empty($actionResult)) { + $this->post(); + return $actionResult; + } else { + $this->post(); + return $this->data; + } + } + + /** + * Checks if the current controller requires privileges and authenticates the user and checks for capabilities + * If the user is not allowed the correct error view is also initialized and the calling method should return + * @uses ->getRequiredCapability and ->getCurrentSiteId + * @param string $capability + * @return boolean + */ + protected function checkCapabilityAndAuthenticateUser($capability) { + if ( !empty($capability) && ! owa_coreAPI::isEveryoneCapable( $capability ) ) { + /* PERFORM AUTHENTICATION */ + $auth = owa_auth::get_instance(); + if (!owa_coreAPI::isCurrentUserAuthenticated()) { + $status = $auth->authenticateUser(); + if ($status['auth_status'] != true) { + $this->notAuthenticatedAction(); + return false; + } + } + + $currentUser = owa_coreAPI::getCurrentUser(); + if (!$currentUser->isCapable($this->getRequiredCapability(),$this->getCurrentSiteId())) { + owa_coreAPI::debug('User does not have capability required by this controller.'); + $this->authenticatedButNotCapableAction(); + //needed? + //$this->set('go', urlencode(owa_lib::get_current_url())); + // needed? -- set auth status for downstream views + //$this->set('auth_status', true); + return false; + } + + } + return true; + } + + // needed? + protected function isEveryoneCapable($capability) { + + return owa_coreAPI::isEveryoneCapable( $capability ); + } + + function logEvent($event_type, $properties) { + + $ed = owa_coreAPI::getEventDispatch(); + + if (!is_a($properties, 'owa_event')) { + + $event = owa_coreAPI::supportClassFactory('base', 'event'); + $event->setProperties($properties); + $event->setEventType($event_type); + } else { + $event = $properties; + } + + return $ed->notify( $event ); + } + + function createValidator() { + + $this->v = owa_coreAPI::supportClassFactory('base', 'validator'); + } + + function addValidation($name, $value, $validation, $conf = array()) { + + if ( empty( $this->v ) ) { + + $this->createValidator(); + } + + return $this->v->addValidation($name, $value, $validation, $conf); + + } + + function setValidation($name, $obj) { + + if (empty($this->v)) { + $this->createValidator(); + } + + return $this->v->setValidation($name, $obj); + } + + function getValidationErrorMsgs() { + + return $this->v->getErrorMsgs(); + + } + + function isAdmin() { + + if ($this->is_admin == true) { + return true; + } + } + + // depricated + function _setCapability($capability) { + + $this->setRequiredCapability($capability); + } + + function setRequiredCapability($capability) { + + $this->capability = $capability; + } + + function getRequiredCapability() { + + return $this->capability; + } + + function getParam($name) { + + if (array_key_exists($name, $this->params)) { + return $this->params[$name]; + } + } + + function setParam($name, $value) { + + $this->params[$name] = $value; + } + + function isParam($name) { + + if (array_key_exists($name, $this->params)) { + return true; + } + } + + function get($name) { + + return $this->getParam($name); + } + + function getAllParams() { + + return $this->params; + } + + function pre() { + + return false; + } + + function post() { + return false; + } + + function getPeriod() { + + return $this->period; + } + + function setPeriod() { + // set period + + $period = $this->makeTimePeriod($this->getParam('period'), $this->params); + + $this->period = $period; + $this->set('period', $this->getPeriod()); + $this->data['params'] = array_merge($this->data['params'], $period->getPeriodProperties()); + } + + function makeTimePeriod($time_period, $params = array()) { + + return owa_coreAPI::makeTimePeriod($time_period, $params); + } + + function setTimePeriod($period) { + + $this->period = $period; + $this->set('period', $this->getPeriod()); + //$this->data['params'] = array_merge($this->data['params'], $period->getPeriodProperties()); + } + + + function setView($view) { + + $this->data['view'] = $view; + } + + function setSubview($subview) { + + $this->data['subview'] = $subview; + + } + + function setViewMethod($method = 'delegate') { + + $this->data['view_method'] = $method; + + } + + function setRedirectAction($do) { + + $this->set('view_method', 'redirect'); + $this->set('do', $do); + + // need to remove these unsets once they are no longer set in the main doAction method + if (array_key_exists('params', $this->data)) { + unset($this->data['params']); + } + if (array_key_exists('site_id', $this->data)) { + // unset($this->data['site_id']); + } + } + + function setPagination($pagination, $name = 'pagination') { + + $this->data[$name] = $pagination; + + } + + function set($name, $value) { + + $this->data[$name] = $value; + } + + function setControllerType($string) { + + $this->type = $string; + + } + + function mergeParams($array) { + + $this->params = array_merge($this->params, $array); + + } + + /** + * redirects borwser to a particular view + * + * @param unknown_type $data + */ + function redirectBrowser($action, $pass_params = true) { + + $control_params = array('view_method', 'auth_status'); + + $get = ''; + + $get .= owa_coreAPI::getSetting('base', 'ns').'do'.'='.$action.'&'; + + if ($pass_params === true) { + + foreach ($this->data as $n => $v) { + + if (!in_array($n, $control_params)) { + + $get .= owa_coreAPI::getSetting('base', 'ns').$n.'='.$v.'&'; + + } + } + } + + $new_url = sprintf(owa_coreAPI::getSetting('base', 'link_template'), owa_coreAPI::getSetting('base', 'main_url'), $get); + + return owa_lib::redirectBrowser($new_url); + + } + + function redirectBrowserToUrl($url) { + + return owa_lib::redirectBrowser($url); + } + + function setStatusCode($code) { + + $this->data['status_code'] = $code; + } + + function setStatusMsg($msg) { + + $this->data['status_message'] = $msg; + } + + function setErrorMsg( $msg ) { + + $this->set( 'error_msg', $msg ); + } + + function authenticatedButNotCapableAction($additionalMessage = '') { + if ( empty($additionalMessage) ) { + $siteIdMsg = $this->getCurrentSiteId(); + if ( empty ($siteIdMsg) ) { + $siteIdMsg = 'No access to any site for the permission "'.$this->getRequiredCapability().'"'; + } + $additionalMessage = $siteIdMsg; + } + $this->setView('base.error'); + $this->set('error_msg', $this->getMsg(2003).' '.$additionalMessage); + } + + function notAuthenticatedAction() { + + $this->setRedirectAction('base.loginForm'); + $this->set('go', urlencode(owa_lib::get_current_url())); + } + + function verifyNonce($nonce) { + + $action = $this->getParam('do'); + + if (!$action) { + $action = $this->getParam('action'); + } + + $matching_nonce = owa_coreAPI::createNonce($action); + owa_coreAPI::debug("passed nonce: $nonce | matching nonce: $matching_nonce"); + if ($nonce === $matching_nonce) { + return true; + } + } + + /** + * Sets nonce flag for the controller. + */ + function setNonceRequired() { + + $this->is_nonce_required = true; + } + + function getSetting($module, $name) { + return owa_coreAPI::getSetting($module, $name); + } + + + /** + * Returns array of owa_site entities where the current user has access to, taken the current controller cap into account + * @return array + */ + protected function getSitesAllowedForCurrentUser() { + owa_coreAPI::debug('get Sites Allowed for user'); + $currentUser = owa_coreAPI::getCurrentUser(); + + if ( $currentUser->isAnonymousUser() || $currentUser->isAdmin() ) { + $result = array(); + $relations = owa_coreAPI::getSitesList(); + + foreach ($relations as $siteRow) { + + $site = owa_coreAPI::entityFactory('base.site'); + $site->load($siteRow['id']); + $result[$siteRow['site_id']] = $site; + } + + return $result; + + } else { + return $currentUser->getAssignedSites(); + } + } + + /** + * gets the siteid taking the site access permissions into account + * If not a typical siteId parameter is set or user lacks permission, the first availabe site is used + * + * @return string or false if no site access + */ + protected function getCurrentSiteId() { + + $siteParameterValue = $this->getSiteIdParameterValue(); + return $siteParameterValue; + } + + /** + * @return integer or false + */ + protected function getSiteIdParameterValue() { + if ($this->getParam('siteId') ) { + return $this->getParam('siteId'); + } + elseif ($this->getParam('site_id') ) { + return $this->getParam('site_id'); + } + return false; + } + +} + ?> \ No newline at end of file diff --git a/owa_coreAPI.php b/owa_coreAPI.php index ca0616c30..9db81d951 100644 --- a/owa_coreAPI.php +++ b/owa_coreAPI.php @@ -1,1690 +1,1690 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_coreAPI { - - - // @depricated - // @todo remove - public static function singleton($params = array()) { - - static $api; - - if(!isset($api)): - $api = new owa_coreAPI(); - endif; - - if(!empty($params)): - $api->params = $params; - endif; - - return $api; - } - - public static function setupStorageEngine($type) { - - if (!class_exists('owa_db')) { - require_once(OWA_BASE_CLASSES_DIR.'owa_db.php'); - } - - if ($type) { - - $connection_class = "owa_db_" . $type; - - if (!class_exists($connection_class)) { - $connection_class_path = OWA_PLUGIN_DIR.'db/' . $connection_class . ".php"; - - if (!require_once($connection_class_path)) { - owa_coreAPI::error(sprintf('Cannot locate proper db class at %s.', $connection_class_path)); - return false; - } - } - - } - - return true; - - } - /** - * @return owa_db - */ - public static function dbSingleton() { - - static $db; - - if (!isset($db)) { - - $db = owa_coreAPI::dbFactory(); - } - - return $db; - } - - public static function dbFactory() { - - $db_type = owa_coreAPI::getSetting('base', 'db_type'); - $ret = owa_coreAPI::setupStorageEngine($db_type); - - if (!$ret) { - owa_coreAPI::error(sprintf('Cannot locate proper db class at %s. Exiting.', $connection_class_path)); - return; - } else { - $connection_class = 'owa_db_'.$db_type; - $db = new $connection_class( - owa_coreAPI::getSetting('base','db_host'), - owa_coreAPI::getSetting('base','db_port'), - owa_coreAPI::getSetting('base','db_name'), - owa_coreAPI::getSetting('base','db_user'), - owa_coreAPI::getSetting('base','db_password'), - owa_coreAPI::getSetting('base','db_force_new_connections'), - owa_coreAPI::getSetting('base','db_make_persistant_connections') - ); - - return $db; - } - } - - /** - * @return owa_settings - */ - public static function configSingleton() { - - static $config; - - if( ! isset( $config ) ) { - - if ( ! class_exists( 'owa_settings' ) ) { - require_once( OWA_BASE_CLASS_DIR.'settings.php' ); - } - - $config = owa_coreAPI::supportClassFactory( 'base', 'settings' ); - } - - return $config; - } - - public static function errorSingleton() { - - static $e; - - if( ! $e ) { - - if ( ! class_exists( 'owa_error' ) ) { - require_once( OWA_BASE_CLASS_DIR.'error.php' ); - } - - $e = owa_coreAPI::supportClassFactory( 'base', 'error' ); - - } - - return $e; - } - - public static function getSetting($module, $name) { - - $s = owa_coreAPI::configSingleton(); - return $s->get($module, $name); - } - - public static function setSetting($module, $name, $value, $persist = false) { - - $s = owa_coreAPI::configSingleton(); - - if ($persist === true) { - $s->persistSetting($module, $name, $value); - } else { - $s->setSetting($module, $name, $value); - } - - } - - public static function persistSetting($module, $name, $value) { - - $s = owa_coreAPI::configSingleton(); - $s->persistSetting($module, $name, $value); - - } - - public static function getSiteSetting($site_id, $name) { - - $site = owa_coreAPI::entityFactory('base.site'); - $site->load( $site->generateId( $site_id ) ); - - if ( $site->wasPersisted() ) { - - return $site->getSiteSetting($name); - } - } - - public static function getRegisteredDomain( $full_domain ) { - - static $psl; - - if ( ! $psl ) { - $psl = owa_coreAPI::supportClassFactory( 'base', 'pslReader' ); - } - - return $psl->getRegisteredDomain( $full_domain ); - } - - public static function persistSiteSetting($site_id, $name, $value) { - - $site = owa_coreAPI::entityFactory('base.site'); - $site->load( $site->generateId( $site_id ) ); - if ( $site->wasPersisted() ) { - $settings = $site->get('settings'); - if ( ! $settings ) { - $settings = array(); - } - $settings[$name] = $value; - $site->set('settings', $settings); - $site->update(); - } - } - - public static function getSiteSettings($site_id) { - - $site = owa_coreAPI::entityFactory('base.site'); - $site->load( $site->generateId( $site_id ) ); - if ( $site->wasPersisted() ) { - - $settings = $site->get('settings'); - - if ( $settings ) { - return $settings; - } else { - return array(); - } - } - - } - - public static function getAllRoles() { - - $caps = owa_coreAPI::getSetting('base', 'capabilities'); - return array_keys($caps); - } - - public static function getCapabilities($role) { - $caps = owa_coreAPI::getSetting('base', 'capabilities'); - if (array_key_exists($role, $caps)) { - return $caps[$role]; - } else { - return array(); - } - } - - /** - * @return owa_serviceUser - */ - public static function getCurrentUser() { - $s = owa_coreAPI::serviceSingleton(); - return $s->getCurrentUser(); - } - - /** - * check to see if the current user has a capability - * always returns a bool - * @return boolean - */ - public static function isCurrentUserCapable($capability, $site_id = null) { - - $cu = owa_coreAPI::getCurrentUser(); - owa_coreAPI::debug("Current User Role: ".$cu->getRole()); - owa_coreAPI::debug("Current User Authentication: ".$cu->isAuthenticated()); - $ret = $cu->isCapable($capability, $site_id); - owa_coreAPI::debug("Is current User capable: ".$ret); - return $ret; - } - - public static function isCurrentUserAuthenticated() { - - $cu = owa_coreAPI::getCurrentUser(); - return $cu->isAuthenticated(); - } - /** - * @return owa_service - */ - public static function serviceSingleton() { - - static $s; - - if(empty($s)) { - - if (!class_exists('owa_service')) { - require_once(OWA_BASE_CLASS_DIR.'service.php'); - } - - $s = owa_coreAPI::supportClassFactory('base', 'service'); - - } - - return $s; - } - - public static function cacheSingleton($params = array()) { - - static $cache; - - if ( !isset ( $cache ) ) { - $cache_type = owa_coreAPI::getSetting('base', 'cacheType'); - - switch ($cache_type) { - - case "memcached": - $implementation = array('owa_memcachedCache', OWA_BASE_CLASS_DIR.'memcachedCache.php'); - break; - default: - $implementation = array('owa_fileCache', OWA_BASE_CLASS_DIR.'fileCache.php'); - - } - - if ( ! class_exists( $implementation[0] ) ) { - require_once( $implementation[1] ); - } - // make this plugable - $cache = new $implementation[0]; - } - - return $cache; - } - - public static function requestContainerSingleton() { - - static $request; - - if(!isset($request)): - - if (!class_exists('owa_requestContainer')): - require_once(OWA_DIR.'owa_requestContainer.php'); - endif; - - $request = owa_lib::factory(OWA_DIR, '', 'owa_requestContainer'); - - endif; - - return $request; - - } - - public static function moduleRequireOnce($module, $class_dir, $file) { - - if (!empty($class_dir)) { - - $class_dir .= '/'; - - } - - $full_file_path = OWA_BASE_DIR.'/modules/'.$module.'/'.$class_dir.$file.'.php'; - - if (file_exists($full_file_path)) { - return require_once($full_file_path); - } else { - owa_coreAPI::debug("moduleRequireOnce says no file found at: $full_file_path"); - return false; - } - } - - public static function moduleFactory($modulefile, $class_suffix = null, $params = '', $class_ns = 'owa_') { - list($module, $file) = explode(".", $modulefile); - $class = $class_ns.$file.$class_suffix; - //print $class; - // Require class file if class does not already exist - if(!class_exists($class)): - owa_coreAPI::moduleRequireOnce($module, '', $file); - endif; - - $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params); - - //if (isset($obj->module)): - $obj->module = $module; - //endif; - - return $obj; - } - - public static function moduleGenericFactory($module, $sub_directory, $file, $class_suffix = null, $params = '', $class_ns = 'owa_') { - - $class = $class_ns.$file.$class_suffix; - - // Require class file if class does not already exist - if(!class_exists($class)): - owa_coreAPI::moduleRequireOnce($module, $sub_directory, $file); - endif; - - $obj = owa_lib::factory(OWA_DIR.'modules'.'/'.$module.'/'.$sub_directory, '', $class, $params); - - return $obj; - } - - /** - * Produces Module Classes (module.php) - * - * @return Object module class object - */ - public static function moduleClassFactory($module) { - - if (!class_exists('owa_module')): - require_once(OWA_BASE_CLASSES_DIR.'owa_module.php'); - endif; - - require_once(OWA_BASE_DIR.'/modules/'.$module.'/module.php'); - - return owa_lib::factory(OWA_BASE_CLASSES_DIR.$module, 'owa_', $module.'Module'); - - } - - - public static function updateFactory($module, $filename, $class_ns = 'owa_') { - - require_once(OWA_BASE_CLASS_DIR.'update.php'); - - //$obj = owa_coreAPI::moduleGenericFactory($module, 'updates', $filename, '_update'); - $class = $class_ns.$module.'_'.$filename.'_update'; - - // Require class file if class does not already exist - if(!class_exists($class)): - owa_coreAPI::moduleRequireOnce($module, 'updates', $filename); - endif; - - $obj = owa_lib::factory(OWA_DIR.'modules'.'/'.$module.'/'.'updates', '', $class); - - $obj->module_name = $module; - if (!$obj->schema_version) { - $obj->schema_version = $filename; - } - return $obj; - } - - public static function subViewFactory($subview, $params = array()) { - - list($module, $class) = explode(".", $subview); - //print_r($module.' ' . $class); - //owa_lib::moduleRequireOnce($module, $class); - - $subview = owa_lib::moduleFactory($subview, 'View', $params); - $subview->is_subview = true; - - return $subview; - } - - public static function supportClassFactory($module, $class, $params = array(),$class_ns = 'owa_') { - - $obj = owa_lib::factory(OWA_BASE_DIR.'/'.'modules'.'/'.$module.'/'.'classes'.'/', $class_ns, $class, $params); - $obj->module = $module; - - return $obj; - - - } - - /** - * Convienence method for generating entities - * - * @param unknown_type $entity_name - * @return unknown - */ - public static function entityFactory($entity_name) { - - /* SETUP STORAGE ENGINE */ - - // Must be called before any entities are created - - if (!defined('OWA_DTD_INT')) { - if (defined('OWA_DB_TYPE')) { - owa_coreAPI::setupStorageEngine(OWA_DB_TYPE); - } else { - owa_coreAPI::setupStorageEngine('mysql'); - } - - } - - - - if (!class_exists('owa_entity')): - require_once(OWA_BASE_CLASSES_DIR.'owa_entity.php'); - endif; - - $entity = owa_coreAPI::moduleSpecificFactory($entity_name, 'entities', '', '', false); - $entity->name = $entity_name; - return $entity; - //return owa_coreAPI::supportClassFactory('base', 'entityManager', $entity_name); - - } - - /** - * Convienence method for generating entities - * - * @param unknown_type $entity_name - * @return unknown - * @depricated - * @todo REMOVE - */ - public static function rawEntityFactory($entity_name) { - - return owa_coreAPI::entityFactory($entity_name); - - } - - /** - * Factory for generating module specific classes - * - * @param string $modulefile - * @param string $class_dir - * @param string $class_suffix - * @param array $params - * @return unknown - */ - public static function moduleSpecificFactory($modulefile, $class_dir, $class_suffix = null, $params = '', $add_module_name = true, $class_ns = 'owa_') { - - list($module, $file) = explode(".", $modulefile); - $class = $class_ns.$file.$class_suffix; - - // Require class file if class does not already exist - if(!class_exists($class)): - owa_coreAPI::moduleRequireOnce($module, $class_dir, $file); - endif; - - $obj = owa_lib::factory(OWA_BASE_DIR.'/'.'modules'.'/'.$class_dir.'/'.$module, '', $class, $params); - - if ($add_module_name == true): - $obj->module = $module; - endif; - - return $obj; - - - } - - public static function executeApiCommand($map) { - - if (!array_key_exists('do', $map)) { - echo ("API Command missing from request."); - owa_coreAPI::debug('API Command missing from request. Aborting.'); - exit; - } else { - // load service - $s = owa_coreAPI::serviceSingleton(); - // lookup method class - $do = $s->getApiMethodClass($map['do']); - - } - - // if exists, pass to OWA as a request - if ($do) { - - if (array_key_exists('args', $do)) { - - $passed_args = array(); - - foreach ($do['args'] as $arg) { - - if (isset($map[$arg])) { - $passed_args[] = $map[$arg]; - } else { - $passed_args[] = ''; - } - } - - if (!empty($do['file'])) { - - if (!class_exists($do['callback'][0])) { - require_once($file); - } - } - - $something = call_user_func_array($do['callback'], $passed_args); - } - - return $something; - } else { - echo "No API Method Found."; - } - - } - - /** - * Convienence method for generating metrics - * - * @param unknown_type $entity_name - * @return unknown - */ - public static function metricFactory($metric_name, $params = array()) { - - if (!strpos($metric_name, '.')) { - $s = owa_coreAPI::serviceSingleton(); - $metric_name = $s->getMetricClasses($metric_name); - } - - if (!class_exists('owa_metric')) { - require_once(OWA_BASE_CLASSES_DIR.'owa_metric.php'); - } - - return owa_coreAPI::moduleSpecificFactory($metric_name, 'metrics', '', $params, false); - } - - /** - * Returns a consolidated list of admin/options panels from all active modules - * - * @return array - */ - public static function getAdminPanels() { - - $panels = array(); - - $service = owa_coreAPI::serviceSingleton(); - - foreach ($service->modules as $k => $v) { - $v->registerAdminPanels(); - $module_panels = $v->getAdminPanels(); - if ($module_panels) { - foreach ($module_panels as $key => $value) { - - $panels[$value['group']][] = $value; - } - } - } - - return $panels; - } - - /** - * Returns a consolidated list of nav links from all active modules for a particular view - * and named navigation element. - * - * @param string nav_name the name of the navigation element that you want links for - * @param string sortby the array value to sort the navigation array by - * @return array - */ - public static function getNavigation($view, $nav_name, $sortby ='order') { - - $links = array(); - - $service = owa_coreAPI::serviceSingleton(); - - foreach ($service->modules as $k => $v) { - - // If the module does not have nav links, register them. needed in case this function is called twice on - // same view. - if (empty($v->nav_links)): - $v->registerNavigation(); - endif; - - $module_nav = $v->getNavigationLinks(); - - - if (!empty($module_nav)) { - // assemble the navigation for a specific view's named navigation element' - foreach ($module_nav as $key => $value) { - - $links[$value['view']][$value['nav_name']][] = $value; - } - } - - } - - //print_r($links[$view][$nav_name]); - if (!empty($links[$view][$nav_name])): - // sort the array - usort($links[$view][$nav_name], function($a, $b) use ($sortby) { - return strnatcmp($a[$sortby], $b[$sortby]); - }); - - return $links[$view][$nav_name]; - else: - return false; - endif; - - } - - public static function getGroupNavigation($group_name, $sortby ='order') { - - $links = array(); - - $service = owa_coreAPI::serviceSingleton(); - - foreach ($service->modules as $k => $v) { - - // If the module does not have nav links, register them. needed in case this function is called twice on - // same view. - if ( empty( $v->nav_links ) ) { - - $v->registerNavigation(); - } - - $module_nav = $v->getNavigationLinks(); - - if ( $module_nav ) { - - //loop through returned nav array - foreach ( $module_nav as $group => $nav_links ) { - - foreach ( $nav_links as $subgroup => $link ) { - - // check to see if group exists - if ( array_key_exists( $group, $links ) ) { - - // check to see if subgroup is already present in the main array - if ( array_key_exists( $subgroup, $links[ $group ] ) ) { - // merge various elements?? not now. - - //check to see if there is an existing set of subgroup links - if ( array_key_exists( 'subgroup', $links[ $group ][ $subgroup ] ) ) { - // if so, merge the subgroups - $links[ $group ][ $subgroup ][ 'subgroup' ] = array_merge( $links[ $group ][ $subgroup ][ 'subgroup' ], $link[ 'subgroup' ] ); - } else { - - } - } else { - // else populate the link - $links[$group][$subgroup] = $link; - } - - } else { - $links[$group][$subgroup] = $link; - } - } - - } - } - } - - if ( isset( $links[$group_name] ) ) { - - return $links[$group_name]; - } - } - - /** - * @Todo REMOVE - */ - public static function getNavSort($a, $b) { - - return strnatcmp($a['order'], $b['order']); - } - - - public static function getActiveModules() { - - $c = owa_coreAPI::configSingleton(); - - $config = $c->config->get('settings'); - - - $active_modules = array(); - - foreach ($config as $k => $module) { - - if ( isset($module['is_active']) && $module['is_active'] == true) { - $active_modules[] = $k; - } - } - - return $active_modules; - - } - - public static function getModulesNeedingUpdates() { - - $service = owa_coreAPI::serviceSingleton(); - - return $service->getModulesNeedingUpdates(); - } - - /** - * Invokes controller to perform controller - * - * @param $action string - * - */ - public static function performAction($action, $params = array()) { - - // Load action from service map - $service = owa_coreAPI::serviceSingleton(); - $action_map = $service->getMapValue('actions', $action ); - - // create the controller object - if ( $action_map ) { - $controller = owa_lib::simpleFactory( $action_map['class_name'], $action_map['file'], $params ); - } else { - // attempt to use old style convention - $controller = owa_coreAPI::moduleFactory($action, 'Controller', $params); - } - - if ( ! $controller || ! method_exists( $controller, 'doAction' ) ) { - - owa_coreAPI::debug("No controller is associated with $action."); - return; - } - - // call the doAction method which is part of the abstract controller class - // inherited by all other controller classes - $data = $controller->doAction(); - - // Display view if controller calls for one. - if ( ! empty( $data['view'] ) || ! empty( $data['action'] ) ) { - - // Redirect to a view - if ( $data['view_method'] == 'redirect' ) { - - return owa_lib::redirectToView( $data ); - - // return an image . Will output headers and binary data. - } elseif ( $data['view_method'] == 'image' ) { - - return owa_coreAPI::displayImage( $data ); - - } else { - - return owa_coreAPI::displayView( $data ); - } - - } elseif( ! empty( $data['do'] ) ) { - - return owa_lib::redirectToView( $data ); - } - } - - /** - * Logs an event to the event queue - * - * take an owa_event object as a message. - * - * @param string $event_type - * @param object $message - * @return boolean - */ - public static function logEvent($event_type, $message = '') { - - // debug - owa_coreAPI::debug("logging event $event_type"); - - if (owa_coreAPI::getSetting('base', 'error_log_level') > 9) { - owa_coreAPI::debug("PHP Server Global: ".print_r($_SERVER, true)); - } - - // Check to see if named users should be logged - if (owa_coreAPI::getSetting('base', 'log_named_users') != true) { - $cu = owa_coreAPI::getCurrentUser(); - $cu_user_id = $cu->getUserData('user_id'); - - if(!empty($cu_user_id)) { - return false; - } - } - - // do not log if the request is robotic - $service = owa_coreAPI::serviceSingleton(); - $bcap = $service->getBrowscap(); - owa_coreAPI::profile(__CLASS__, __FUNCTION__, __LINE__); - if (!owa_coreAPI::getSetting('base', 'log_robots')) { - - if ($bcap->robotCheck()) { - owa_coreAPI::debug("ABORTING: request appears to be from a robot"); - owa_coreAPI::setRequestParam('is_robot', true); - return; - } - owa_coreAPI::profile(__CLASS__, __FUNCTION__, __LINE__); - } - - // form event if one was not passed - $class= 'owa_event'; - if (!($message instanceof $class)) { - $event = owa_coreAPI::supportClassFactory('base', 'event'); - $event->setProperties($message); - $event->setEventType($event_type); - } else { - $event = $message; - } - - // STAGE 1 - set environmental properties from SERVER - $teh = owa_coreAPI::getInstance( 'owa_trackingEventHelpers', OWA_BASE_CLASS_DIR.'trackingEventHelpers.php'); - $environmentals = $service->getMap( 'tracking_properties_environmental' ); - $teh->setTrackerProperties( $event, $environmentals ); - - // Filter XSS exploits from event properties - //$event->cleanProperties(); - - // do not log if the do not log property is set on the event. - if ($event->get('do_not_log')) { - return false; - } - - // check to see if IP should be excluded - if ( owa_coreAPI::isIpAddressExcluded( $event->get('ip_address') ) ) { - owa_coreAPI::debug("Not logging event. IP address found in exclusion list."); - return false; - } - - // queue for later or process event straight away - if ( owa_coreAPI::getSetting( 'base', 'queue_events' ) || - owa_coreAPI::getSetting( 'base', 'queue_incoming_tracking_events' ) ) { - - $q = owa_coreAPI::getEventQueue( 'incoming_tracking_events' ); - owa_coreAPI::debug('Queuing '.$event->getEventType().' event with properties: '.print_r($event->getProperties(), true ) ); - $q->sendMessage( $event ); - - } else { - - // lookup which event processor to use to process this event type - $processor_action = owa_coreAPI::getEventProcessor( $event->getEventType() ); - return owa_coreAPI::handleRequest( array( 'event' => $event ), $processor_action ); - } - } - - public static function getInstance( $class, $path ) { - - if ( ! class_exists( $class ) ) { - - require_once( $path ); - } - - return $class::getInstance(); - } - - public static function displayImage($data) { - - header('Content-type: image/gif'); - header('P3P: CP="'.owa_coreAPI::getSetting('base', 'p3p_policy').'"'); - header('Expires: Sat, 22 Apr 1978 02:19:00 GMT'); - header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); - header('Cache-Control: no-store, no-cache, must-revalidate'); - header('Pragma: no-cache'); - - echo owa_coreAPI::displayView($data); - } - - - /** - * Displays a View without user authentication. Takes array of data as input - * - * @param array $data - * @param string $viewfile a specific view file to use - * @return string - * - */ - public static function displayView($data, $viewfile = '') { - - if (empty($viewfile)): - $viewfile = $data['view']; - endif; - - $view = owa_coreAPI::moduleFactory($viewfile, 'View'); - $view->setData($data); - return $view->assembleView($data); - - } - - public static function displaySubView($data, $viewfile = '') { - - if (empty($viewfile)): - $viewfile = $data['view']; - endif; - - $view = owa_coreAPI::subViewFactory($viewfile); - - return $view->assembleView($data); - - } - - /** - * Strip a URL of certain GET params - * @depricated - * @return string - * @todo REMOVE - */ - function stripDocumentUrl($url) { - - if (owa_coreAPI::getSetting('base', 'clean_query_string')): - - if (owa_coreAPI::getSetting('base', 'query_string_filters')): - $filters = str_replace(' ', '', owa_coreAPI::getSetting('base', 'query_string_filters')); - $filters = explode(',', $filters); - else: - $filters = array(); - endif; - - // OWA specific params to filter - array_push($filters, owa_coreAPI::getSetting('base', 'source_param')); - array_push($filters, owa_coreAPI::getSetting('base', 'ns').owa_coreAPI::getSetting('base', 'feed_subscription_param')); - - //print_r($filters); - - foreach ($filters as $filter => $value) { - - $url = preg_replace( - '#\?' . - $value . - '=.*$|&' . - $value . - '=.*$|' . - $value . - '=.*&#msiU', - '', - $url - ); - - } - - endif; - //print $url; - - return $url; - - } - - public static function getRequestParam($name) { - - $service = owa_coreAPI::serviceSingleton(); - - return $service->request->getParam($name); - - } - - public static function getRequest() { - $service = owa_coreAPI::serviceSingleton(); - return $service->request; - } - - public static function setRequestParam($name, $value) { - - $service = owa_coreAPI::serviceSingleton(); - return $service->request->setParam($name, $value); - - } - - public static function makeTimePeriod($time_period, $params = array()) { - - $period = owa_coreAPI::supportClassFactory('base', 'timePeriod'); - - if ( ! array_key_exists('period', $params)) { - $params['period'] = $time_period; - } - $period->setFromMap( $params ); - return $period; - } - - /** - * Factory method for producing validation objects - * - * @return Object - */ - public static function validationFactory($class_file) { - - if (!class_exists('owa_validation')): - require_once(OWA_BASE_CLASS_DIR.'validation.php'); - endif; - - return owa_lib::factory(OWA_PLUGIN_DIR.'validations', 'owa_', $class_file, array(), 'Validation'); - - } - - public static function debug($msg) { - - $e = owa_coreAPI::errorSingleton(); - $e->debug($msg); - return; - } - - public static function error($msg) { - - $e = owa_coreAPI::errorSingleton(); - $e->err($msg); - return; - } - - public static function notice($msg) { - - $e = owa_coreAPI::errorSingleton(); - $e->notice($msg); - return; - } - - public static function createCookie($cookie_name, $cookie_value, $expires = 0, $path = '/', $domain = '') { - - if ( $domain ) { - // sanitizes the domain - $domain = owa_lib::sanitizeCookieDomain( $domain ); - } else { - $domain = owa_coreAPI::getSetting('base', 'cookie_domain'); - } - if (is_array($cookie_value)) { - - $cookie_value = owa_lib::implode_assoc('=>', '|||', $cookie_value); - } - - // add namespace - $cookie_name = sprintf('%s%s', owa_coreAPI::getSetting('base', 'ns'), $cookie_name); - - // debug - owa_coreAPI::debug(sprintf('Setting cookie %s with values: %s under domain: %s', $cookie_name, $cookie_value, $domain)); - - // makes cookie to session cookie only - if (!owa_coreAPI::getSetting('base', 'cookie_persistence')) { - $expires = 0; - } - - // set compact privacy header - header(sprintf('P3P: CP="%s"', owa_coreAPI::getSetting('base', 'p3p_policy'))); - //owa_coreAPI::debug('time: '.$expires); - setcookie($cookie_name, $cookie_value, $expires, $path, $domain); - return; - } - - public static function deleteCookie($cookie_name, $path = '/', $domain = '') { - - return owa_coreAPI::createCookie($cookie_name, false, time()-3600*25, $path, $domain); - } - - public static function registerStateStore($name, $expiration, $length = '', $format = '', $type = 'cookie', $cdh_required = '') { - - $service = owa_coreAPI::serviceSingleton(); - return $service->request->state->registerStore( $name, $expiration, $length, $format, $type, $cdh_required ); - } - - public static function setState($store, $name = '', $value, $store_type = '', $is_perminent = '') { - - $service = owa_coreAPI::serviceSingleton(); - return $service->request->state->set($store, $name, $value, $store_type, $is_perminent); - } - - public static function getState($store, $name = '') { - - $service = owa_coreAPI::serviceSingleton(); - return $service->request->state->get($store, $name); - } - - // depricated - public static function getStateParam($store, $name = '') { - - return owa_coreAPI::getState($store, $name); - } - - public static function getServerParam($name = '') { - - $service = owa_coreAPI::serviceSingleton(); - return $service->request->getServerParam($name); - } - - public static function clearState($store, $name = '') { - - $service = owa_coreAPI::serviceSingleton(); - $service->request->state->clear($store, $name); - - } - - public static function getEventProcessor($event_type) { - - $service = owa_coreAPI::serviceSingleton(); - $processor = $service->getMapValue('event_processors', $event_type); - - if (empty($processor)) { - - $processor = 'base.processEvent'; - } - - return $processor; - } - - /** - * Retrieves any registered build packages - * - * @return array - */ - public static function getBuildPackages() { - - $service = owa_coreAPI::serviceSingleton(); - $map = $service->getMap('build_packages'); - - if ( ! $map ) { - $map = array(); - } - - return $map; - } - - /** - * Handles OWA internal page/action requests - * - * @return unknown - */ - public static function handleRequest($caller_params = null, $action = '') { - - static $init; - - $service = owa_coreAPI::serviceSingleton(); - // Override request parsms with those passed by caller - if (!empty($caller_params)) { - $service->request->mergeParams($caller_params); - }; - - $params = $service->request->getAllOwaParams(); - - if ($init != true) { - owa_coreAPI::debug('Handling request with params: '. print_r($params, true)); - } - - // backwards compatability with old style view/controler scheme - // still needed?? - if (array_key_exists('view', $params)) { - // its a view request so the only data is in whats in the params - $init = true; - return owa_coreAPI::displayView($params); - } - - if (empty($action)) { - $action = owa_coreAPI::getRequestParam('action'); - if (empty($action)) { - $action = owa_coreAPI::getRequestParam('do'); - - if (empty($action)) { - $action = owa_coreAPI::getSetting('base', 'start_page'); - $params['do'] = $action; - } - } - } - - $init = true; - owa_coreAPI::debug('About to perform action: '.$action); - return owa_coreAPI::performAction($action, $params); - - } - - public static function isUpdateRequired() { - - $service = owa_coreAPI::serviceSingleton(); - return $service->isUpdateRequired(); - } - - /** - * @return array - */ - public static function getSitesList() { - $db = owa_coreAPI::dbSingleton(); - $db->selectFrom('owa_site'); - $db->selectColumn('*'); - $sites = $db->getAllRows(); - - if ( ! $sites ) { - $sites = array(); - } - return $sites; - } - - public static function profile($that = '', $function = '', $line = '', $msg = '') { - - if (defined('OWA_PROFILER')) { - if (OWA_PROFILER === true) { - - static $profiler; - - if (!class_exists('PhpQuickProfiler')) { - require_once(OWA_INCLUDE_DIR.'pqp/classes/PhpQuickProfiler.php'); - } - - if (empty($profiler)) { - $profiler = new PhpQuickProfiler(PhpQuickProfiler::getMicroTime(), OWA_INCLUDE_DIR.'pqp/'); - } - - $class = get_class($that); - Console::logSpeed($class."::$function - Line: $line - Msg: $msg"); - Console::logMemory($that, $class. "::$function - Line: $line"); - - return $profiler; - } - } - } - - public static function profileDisplay() { - $p = owa_coreAPI::profile(); - if ($p) { - $p->display(); - } - - } - - public static function getEventDispatch() { - - if (! class_exists( 'owa_eventDispatch' ) ) { - require_once(OWA_BASE_CLASS_DIR.'eventDispatch.php'); - } - - return owa_eventDispatch::get_instance(); - - } - - public static function getEventQueue( $name ) { - - static $queues; - - // make queue if needed - if ( ! isset( $queues[ $name ] ) ) { - - // get queue config - $s = owa_coreAPI::serviceSingleton(); - $map = $s->getMapValue('event_queues', $name); - - if ( $map ) { - - $implementation = $s->getMapValue( 'event_queue_types', $map['queue_type'] ); - - if ( $implementation - && isset( $implementation[0] ) - && isset( $implementation[1] ) - ) { - owa_coreAPI::debug(print_r($implementation, true)); - $queues[ $name ] = owa_lib::simpleFactory( $implementation[0], $implementation[1], $map ); - - } else { - - throw new Exception("No event queue by that type found."); - } - - } else { - - throw new Exception("No configuration found for event queue $name."); - } - } - // return queue - return $queues[ $name ]; - } - - public static function getCliCommandClass($command) { - - $s = owa_coreAPI::serviceSingleton(); - return $s->getCliCommandClass($command); - } - - public static function getGeolocationFromIpAddress($ip_address) { - - $s = owa_coreAPI::serviceSingleton(); - $s->geolocation->getGeolocationFromIp($ip_address); - return $s->geolocation; - } - - public static function getNonceTimeInterval() { - - return ceil( time() / owa_coreAPI::getSetting( 'base', 'nonce_expiration_period') ); - } - - public static function createNonce($action) { - - $time = owa_coreAPI::getNonceTimeInterval(); - $cu = owa_coreAPI::getCurrentUser(); - $user_id = $cu->getUserData( 'user_id' ); - - $full_nonce = $time . $action . $user_id . 'owa_nonce'; - - $nonce = substr( owa_coreAPI::saltedHash($full_nonce, 'nonce'), -12, 10); - - return $nonce; - } - - public static function saltedHash( $data, $scheme, $hash_type = 'md5' ) { - - $salt = owa_coreAPI::getSalt( $scheme ); - return owa_lib::hash( $hash_type, $data, $salt ); - } - - - - public static function getSalt( $scheme ) { - - static $cached_salts; - - $scheme = strtoupper($scheme); - - if ( ! $cached_salts ) { - - $cached_salts = array(); - $ns = strtoupper( owa_coreAPI::getSetting('base', 'ns') ); - - foreach (array('NONCE', 'SECRET', 'AUTH') as $f ) { - - foreach (array('KEY', 'SALT') as $s ) { - - $const = sprintf("%s%s_%s", $ns, $f, $s); - - if ( ! defined ( "$const" ) ) { - continue; - } else { - - $cached_salts[ $f.'_'.$s ] = constant("$const"); - } - } - } - } - - - $key = ''; - $salt = ''; - - if (array_key_exists( $scheme.'_KEY', $cached_salts ) ) { - - $key = $cached_salts[ $scheme.'_KEY' ]; - } - - if (array_key_exists( $scheme.'_SALT', $cached_salts ) ) { - - $salt = $cached_salts[ $scheme.'_SALT' ]; - } - - return $key . $salt; - } - - public static function secureRandomString( $length, $special_chars = true, $more_special_chars = true ) { - - $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - if ( $special_chars ) - $chars .= '!@#$%^&*()'; - if ( $more_special_chars ) - $chars .= '-_ []{}<>~`+=,.;:/?|'; - - $password = ''; - for ( $i = 0; $i < $length; $i++ ) { - $password .= substr($chars, owa_coreAPI::random(0, strlen($chars) - 1), 1); - } - - return $password; - } - - public static function random($min, $max) { - - static $rnd_value; - - if ( strlen($rnd_value) < 8 ) { - - $notrandom = false; - - if ( function_exists( 'openssl_random_pseudo_bytes' ) ) { - - $rnd_value = bin2hex(openssl_random_pseudo_bytes(32, $cstrong)); - - if ( ! $cstrong ) { - - $notrandom = true; - } - - } else { - - $notrandom = true; - } - - if ( $notrandom ) { - - $seed = microtime(); - $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed ); - $rnd_value .= sha1($rnd_value); - $rnd_value .= sha1($rnd_value . $seed); - - } - - //$seed = md5($seed . $rnd_value); - } - // Take the first 8 digits for our value - $value = substr($rnd_value, 0, 8); - - // Strip the first eight, leaving the remainder for the next call to random. - $rnd_value = substr($rnd_value, 8); - - $value = abs(hexdec($value)); - - // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats. - $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff - - // Reduce the value to be within the min - max range - if ( $max != 0 ) - $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 ); - - return abs(intval($value)); - } - - public static function summarize($map) { - - $entity = owa_coreAPI::entityFactory($map['entity']); - $db = owa_coreAPI::dbSingleton(); - $db->selectFrom($entity->getTableName(), $entity->getTableAlias()); - - foreach ($map['columns'] as $col => $action) { - - switch ($action) { - - case 'sum': - $col_def = sprintf("SUM(%s)", $col); - $name = $col.'_sum'; - break; - case 'count': - $col_def = sprintf("COUNT(%s)", $col); - $name = $col.'_count'; - break; - case 'count_distinct': - $col_def = sprintf("COUNT(distinct %s)", $col); - $name = $col.'_dcount'; - break; - case 'max': - $col_def = sprintf("MAX(%s)", $col); - $name = $col.'_max'; - break; - } - - $db->selectColumn($col_def, $name); - } - - foreach ($map['constraints'] as $con_col => $con_value) { - - if ( is_array( $con_value ) ) { - $db->where($con_col, $con_value['value'], $con_value['operator']); - } else { - $db->where($con_col, $con_value); - } - } - - $ret = $db->getOneRow(); - return $ret; - } - - public static function getJsTrackerTag( $site_id, $options = array() ) { - - if ( ! class_exists( 'owa_template' ) ) { - require_once(OWA_BASE_CLASSES_DIR.'owa_template.php'); - } - - $t = new owa_template(); - - if (owa_coreAPI::getSetting('base', 'is_embedded')) { - - // needed to override the endpoint used by the js tracker - $options['apiEndpoint'] = owa_coreAPI::getSetting('base', 'api_url'); - } - - $t->set( 'site_id', $site_id ); - $cmds = owa_coreAPI::filter( 'tracker_tag_cmds', array() ); - $t->set( 'cmds', $cmds ); - $t->set('options', $options); - $t->set_template('js_log_tag.tpl'); - return $t->fetch(); - } - - public static function activateModule( $module_name ) { - - if ( $module_name ) { - - $m = owa_coreAPI::moduleClassFactory($module_name); - return $m->activate(); - } - } - - public static function deactivateModule( $module_name ) { - - if ( $module_name ) { - - $s = owa_coreAPI::serviceSingleton(); - $m = $s->getModule($module_name); - return $m->deactivate(); - } - } - - public static function installModule( $module_name ) { - - if ($module_name) { - - $m = owa_coreAPI::moduleClassFactory($module_name); - $status = $m->install(); - return $status; - } - } - - public static function generateInstanceSpecificHash() { - - if ( defined( 'OWA_SECRET' ) ) { - $salt = OWA_SECRET; - } else { - $salt = ''; - } - - if ( defined( 'OWA_DB_USER' ) ) { - $salt .= OWA_DB_USER; - } - - if ( defined( 'OWA_DB_PASSWORD' ) ) { - $salt .= OWA_DB_PASSWORD; - } - - return md5( $salt ); - } - - public static function getAllDimensions() { - - $s = owa_coreAPI::serviceSingleton(); - - $dims = $s->dimensions; - - foreach ( $s->denormalizedDimensions as $k => $entity_dims ) { - foreach ($entity_dims as $entity => $dedim) { - $dims[$k] = $dedim; - } - } - - return $dims; - } - - public static function getAllMetrics() { - - $s = owa_coreAPI::serviceSingleton(); - return $s->metrics; - } - - public static function getGoalManager( $siteId ) { - - static $gm; - - if ( ! $gm ) { - - $gm = array(); - } - - if ( ! isset( $gm[$siteId] ) ) { - $gm[ $siteId ] = owa_coreAPI::supportClassFactory('base', 'goalManager', $siteId); - } - - return $gm[$siteId]; - } - - public static function getRequestTimestamp() { - - $r = owa_coreAPI::requestContainerSingleton(); - return $r->getTimestamp(); - } - - public static function isEveryoneCapable( $capability ) { - - $caps = owa_coreAPI::getCapabilities('everyone'); - - if ( in_array( $capability, $caps ) ) { - return true; - } else { - return false; - } - } - - public static function getCurrentUrl() { - $r = owa_coreAPI::requestContainerSingleton(); - return $r->getCurrentUrl(); - } - - public static function isIpAddressExcluded( $ip_address ) { - - // do not log if ip address is on the do not log list - $ips = owa_coreAPI::getSetting( 'base', 'excluded_ips' ); - owa_coreAPI::debug('excluded ips: '.$ips); - if ( $ips ) { - - $ips = trim( $ips ); - - if ( strpos( $ips, ',' ) ) { - $ips = explode( ',', $ips ); - } else { - $ips = array( $ips ); - } - - foreach( $ips as $ip ) { - $ip = trim( $ip ); - if ( $ip_address === $ip ) { - owa_coreAPI::debug("Request is from excluded ip address: $ip."); - return true; - } - } - } - } - - /** - * Attaches an event handler to the event queue - * - * @param array $event_name - * @param string $handler_name - * @return boolean - */ - public static function registerFilter( $filter_name, $callback, $priority = 10 ) { - - $ed = owa_coreAPI::getEventDispatch(); - $ed->attachFilter($filter_name, $callback, $priority); - } - - public static function filter( $filter_name, $value ) { - - $ed = owa_coreAPI::getEventDispatch(); - return $ed->filter( $filter_name, $value ); - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_coreAPI { + + + // @depricated + // @todo remove + public static function singleton($params = array()) { + + static $api; + + if(!isset($api)): + $api = new owa_coreAPI(); + endif; + + if(!empty($params)): + $api->params = $params; + endif; + + return $api; + } + + public static function setupStorageEngine($type) { + + if (!class_exists('owa_db')) { + require_once(OWA_BASE_CLASSES_DIR.'owa_db.php'); + } + + if ($type) { + + $connection_class = "owa_db_" . $type; + + if (!class_exists($connection_class)) { + $connection_class_path = OWA_PLUGIN_DIR.'db/' . $connection_class . ".php"; + + if (!require_once($connection_class_path)) { + owa_coreAPI::error(sprintf('Cannot locate proper db class at %s.', $connection_class_path)); + return false; + } + } + + } + + return true; + + } + /** + * @return owa_db + */ + public static function dbSingleton() { + + static $db; + + if (!isset($db)) { + + $db = owa_coreAPI::dbFactory(); + } + + return $db; + } + + public static function dbFactory() { + + $db_type = owa_coreAPI::getSetting('base', 'db_type'); + $ret = owa_coreAPI::setupStorageEngine($db_type); + + if (!$ret) { + owa_coreAPI::error(sprintf('Cannot locate proper db class at %s. Exiting.', $connection_class_path)); + return; + } else { + $connection_class = 'owa_db_'.$db_type; + $db = new $connection_class( + owa_coreAPI::getSetting('base','db_host'), + owa_coreAPI::getSetting('base','db_port'), + owa_coreAPI::getSetting('base','db_name'), + owa_coreAPI::getSetting('base','db_user'), + owa_coreAPI::getSetting('base','db_password'), + owa_coreAPI::getSetting('base','db_force_new_connections'), + owa_coreAPI::getSetting('base','db_make_persistant_connections') + ); + + return $db; + } + } + + /** + * @return owa_settings + */ + public static function configSingleton() { + + static $config; + + if( ! isset( $config ) ) { + + if ( ! class_exists( 'owa_settings' ) ) { + require_once( OWA_BASE_CLASS_DIR.'settings.php' ); + } + + $config = owa_coreAPI::supportClassFactory( 'base', 'settings' ); + } + + return $config; + } + + public static function errorSingleton() { + + static $e; + + if( ! $e ) { + + if ( ! class_exists( 'owa_error' ) ) { + require_once( OWA_BASE_CLASS_DIR.'error.php' ); + } + + $e = owa_coreAPI::supportClassFactory( 'base', 'error' ); + + } + + return $e; + } + + public static function getSetting($module, $name) { + + $s = owa_coreAPI::configSingleton(); + return $s->get($module, $name); + } + + public static function setSetting($module, $name, $value, $persist = false) { + + $s = owa_coreAPI::configSingleton(); + + if ($persist === true) { + $s->persistSetting($module, $name, $value); + } else { + $s->setSetting($module, $name, $value); + } + + } + + public static function persistSetting($module, $name, $value) { + + $s = owa_coreAPI::configSingleton(); + $s->persistSetting($module, $name, $value); + + } + + public static function getSiteSetting($site_id, $name) { + + $site = owa_coreAPI::entityFactory('base.site'); + $site->load( $site->generateId( $site_id ) ); + + if ( $site->wasPersisted() ) { + + return $site->getSiteSetting($name); + } + } + + public static function getRegisteredDomain( $full_domain ) { + + static $psl; + + if ( ! $psl ) { + $psl = owa_coreAPI::supportClassFactory( 'base', 'pslReader' ); + } + + return $psl->getRegisteredDomain( $full_domain ); + } + + public static function persistSiteSetting($site_id, $name, $value) { + + $site = owa_coreAPI::entityFactory('base.site'); + $site->load( $site->generateId( $site_id ) ); + if ( $site->wasPersisted() ) { + $settings = $site->get('settings'); + if ( ! $settings ) { + $settings = array(); + } + $settings[$name] = $value; + $site->set('settings', $settings); + $site->update(); + } + } + + public static function getSiteSettings($site_id) { + + $site = owa_coreAPI::entityFactory('base.site'); + $site->load( $site->generateId( $site_id ) ); + if ( $site->wasPersisted() ) { + + $settings = $site->get('settings'); + + if ( $settings ) { + return $settings; + } else { + return array(); + } + } + + } + + public static function getAllRoles() { + + $caps = owa_coreAPI::getSetting('base', 'capabilities'); + return array_keys($caps); + } + + public static function getCapabilities($role) { + $caps = owa_coreAPI::getSetting('base', 'capabilities'); + if (array_key_exists($role, $caps)) { + return $caps[$role]; + } else { + return array(); + } + } + + /** + * @return owa_serviceUser + */ + public static function getCurrentUser() { + $s = owa_coreAPI::serviceSingleton(); + return $s->getCurrentUser(); + } + + /** + * check to see if the current user has a capability + * always returns a bool + * @return boolean + */ + public static function isCurrentUserCapable($capability, $site_id = null) { + + $cu = owa_coreAPI::getCurrentUser(); + owa_coreAPI::debug("Current User Role: ".$cu->getRole()); + owa_coreAPI::debug("Current User Authentication: ".$cu->isAuthenticated()); + $ret = $cu->isCapable($capability, $site_id); + owa_coreAPI::debug("Is current User capable: ".$ret); + return $ret; + } + + public static function isCurrentUserAuthenticated() { + + $cu = owa_coreAPI::getCurrentUser(); + return $cu->isAuthenticated(); + } + /** + * @return owa_service + */ + public static function serviceSingleton() { + + static $s; + + if(empty($s)) { + + if (!class_exists('owa_service')) { + require_once(OWA_BASE_CLASS_DIR.'service.php'); + } + + $s = owa_coreAPI::supportClassFactory('base', 'service'); + + } + + return $s; + } + + public static function cacheSingleton($params = array()) { + + static $cache; + + if ( !isset ( $cache ) ) { + $cache_type = owa_coreAPI::getSetting('base', 'cacheType'); + + switch ($cache_type) { + + case "memcached": + $implementation = array('owa_memcachedCache', OWA_BASE_CLASS_DIR.'memcachedCache.php'); + break; + default: + $implementation = array('owa_fileCache', OWA_BASE_CLASS_DIR.'fileCache.php'); + + } + + if ( ! class_exists( $implementation[0] ) ) { + require_once( $implementation[1] ); + } + // make this plugable + $cache = new $implementation[0]; + } + + return $cache; + } + + public static function requestContainerSingleton() { + + static $request; + + if(!isset($request)): + + if (!class_exists('owa_requestContainer')): + require_once(OWA_DIR.'owa_requestContainer.php'); + endif; + + $request = owa_lib::factory(OWA_DIR, '', 'owa_requestContainer'); + + endif; + + return $request; + + } + + public static function moduleRequireOnce($module, $class_dir, $file) { + + if (!empty($class_dir)) { + + $class_dir .= '/'; + + } + + $full_file_path = OWA_BASE_DIR.'/modules/'.$module.'/'.$class_dir.$file.'.php'; + + if (file_exists($full_file_path)) { + return require_once($full_file_path); + } else { + owa_coreAPI::debug("moduleRequireOnce says no file found at: $full_file_path"); + return false; + } + } + + public static function moduleFactory($modulefile, $class_suffix = null, $params = '', $class_ns = 'owa_') { + list($module, $file) = explode(".", $modulefile); + $class = $class_ns.$file.$class_suffix; + //print $class; + // Require class file if class does not already exist + if(!class_exists($class)): + owa_coreAPI::moduleRequireOnce($module, '', $file); + endif; + + $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params); + + //if (isset($obj->module)): + $obj->module = $module; + //endif; + + return $obj; + } + + public static function moduleGenericFactory($module, $sub_directory, $file, $class_suffix = null, $params = '', $class_ns = 'owa_') { + + $class = $class_ns.$file.$class_suffix; + + // Require class file if class does not already exist + if(!class_exists($class)): + owa_coreAPI::moduleRequireOnce($module, $sub_directory, $file); + endif; + + $obj = owa_lib::factory(OWA_DIR.'modules'.'/'.$module.'/'.$sub_directory, '', $class, $params); + + return $obj; + } + + /** + * Produces Module Classes (module.php) + * + * @return Object module class object + */ + public static function moduleClassFactory($module) { + + if (!class_exists('owa_module')): + require_once(OWA_BASE_CLASSES_DIR.'owa_module.php'); + endif; + + require_once(OWA_BASE_DIR.'/modules/'.$module.'/module.php'); + + return owa_lib::factory(OWA_BASE_CLASSES_DIR.$module, 'owa_', $module.'Module'); + + } + + + public static function updateFactory($module, $filename, $class_ns = 'owa_') { + + require_once(OWA_BASE_CLASS_DIR.'update.php'); + + //$obj = owa_coreAPI::moduleGenericFactory($module, 'updates', $filename, '_update'); + $class = $class_ns.$module.'_'.$filename.'_update'; + + // Require class file if class does not already exist + if(!class_exists($class)): + owa_coreAPI::moduleRequireOnce($module, 'updates', $filename); + endif; + + $obj = owa_lib::factory(OWA_DIR.'modules'.'/'.$module.'/'.'updates', '', $class); + + $obj->module_name = $module; + if (!$obj->schema_version) { + $obj->schema_version = $filename; + } + return $obj; + } + + public static function subViewFactory($subview, $params = array()) { + + list($module, $class) = explode(".", $subview); + //print_r($module.' ' . $class); + //owa_lib::moduleRequireOnce($module, $class); + + $subview = owa_lib::moduleFactory($subview, 'View', $params); + $subview->is_subview = true; + + return $subview; + } + + public static function supportClassFactory($module, $class, $params = array(),$class_ns = 'owa_') { + + $obj = owa_lib::factory(OWA_BASE_DIR.'/'.'modules'.'/'.$module.'/'.'classes'.'/', $class_ns, $class, $params); + $obj->module = $module; + + return $obj; + + + } + + /** + * Convienence method for generating entities + * + * @param unknown_type $entity_name + * @return unknown + */ + public static function entityFactory($entity_name) { + + /* SETUP STORAGE ENGINE */ + + // Must be called before any entities are created + + if (!defined('OWA_DTD_INT')) { + if (defined('OWA_DB_TYPE')) { + owa_coreAPI::setupStorageEngine(OWA_DB_TYPE); + } else { + owa_coreAPI::setupStorageEngine('mysql'); + } + + } + + + + if (!class_exists('owa_entity')): + require_once(OWA_BASE_CLASSES_DIR.'owa_entity.php'); + endif; + + $entity = owa_coreAPI::moduleSpecificFactory($entity_name, 'entities', '', '', false); + $entity->name = $entity_name; + return $entity; + //return owa_coreAPI::supportClassFactory('base', 'entityManager', $entity_name); + + } + + /** + * Convienence method for generating entities + * + * @param unknown_type $entity_name + * @return unknown + * @depricated + * @todo REMOVE + */ + public static function rawEntityFactory($entity_name) { + + return owa_coreAPI::entityFactory($entity_name); + + } + + /** + * Factory for generating module specific classes + * + * @param string $modulefile + * @param string $class_dir + * @param string $class_suffix + * @param array $params + * @return unknown + */ + public static function moduleSpecificFactory($modulefile, $class_dir, $class_suffix = null, $params = '', $add_module_name = true, $class_ns = 'owa_') { + + list($module, $file) = explode(".", $modulefile); + $class = $class_ns.$file.$class_suffix; + + // Require class file if class does not already exist + if(!class_exists($class)): + owa_coreAPI::moduleRequireOnce($module, $class_dir, $file); + endif; + + $obj = owa_lib::factory(OWA_BASE_DIR.'/'.'modules'.'/'.$class_dir.'/'.$module, '', $class, $params); + + if ($add_module_name == true): + $obj->module = $module; + endif; + + return $obj; + + + } + + public static function executeApiCommand($map) { + + if (!array_key_exists('do', $map)) { + echo ("API Command missing from request."); + owa_coreAPI::debug('API Command missing from request. Aborting.'); + exit; + } else { + // load service + $s = owa_coreAPI::serviceSingleton(); + // lookup method class + $do = $s->getApiMethodClass($map['do']); + + } + + // if exists, pass to OWA as a request + if ($do) { + + if (array_key_exists('args', $do)) { + + $passed_args = array(); + + foreach ($do['args'] as $arg) { + + if (isset($map[$arg])) { + $passed_args[] = $map[$arg]; + } else { + $passed_args[] = ''; + } + } + + if (!empty($do['file'])) { + + if (!class_exists($do['callback'][0])) { + require_once($file); + } + } + + $something = call_user_func_array($do['callback'], $passed_args); + } + + return $something; + } else { + echo "No API Method Found."; + } + + } + + /** + * Convienence method for generating metrics + * + * @param unknown_type $entity_name + * @return unknown + */ + public static function metricFactory($metric_name, $params = array()) { + + if (!strpos($metric_name, '.')) { + $s = owa_coreAPI::serviceSingleton(); + $metric_name = $s->getMetricClasses($metric_name); + } + + if (!class_exists('owa_metric')) { + require_once(OWA_BASE_CLASSES_DIR.'owa_metric.php'); + } + + return owa_coreAPI::moduleSpecificFactory($metric_name, 'metrics', '', $params, false); + } + + /** + * Returns a consolidated list of admin/options panels from all active modules + * + * @return array + */ + public static function getAdminPanels() { + + $panels = array(); + + $service = owa_coreAPI::serviceSingleton(); + + foreach ($service->modules as $k => $v) { + $v->registerAdminPanels(); + $module_panels = $v->getAdminPanels(); + if ($module_panels) { + foreach ($module_panels as $key => $value) { + + $panels[$value['group']][] = $value; + } + } + } + + return $panels; + } + + /** + * Returns a consolidated list of nav links from all active modules for a particular view + * and named navigation element. + * + * @param string nav_name the name of the navigation element that you want links for + * @param string sortby the array value to sort the navigation array by + * @return array + */ + public static function getNavigation($view, $nav_name, $sortby ='order') { + + $links = array(); + + $service = owa_coreAPI::serviceSingleton(); + + foreach ($service->modules as $k => $v) { + + // If the module does not have nav links, register them. needed in case this function is called twice on + // same view. + if (empty($v->nav_links)): + $v->registerNavigation(); + endif; + + $module_nav = $v->getNavigationLinks(); + + + if (!empty($module_nav)) { + // assemble the navigation for a specific view's named navigation element' + foreach ($module_nav as $key => $value) { + + $links[$value['view']][$value['nav_name']][] = $value; + } + } + + } + + //print_r($links[$view][$nav_name]); + if (!empty($links[$view][$nav_name])): + // sort the array + usort($links[$view][$nav_name], function($a, $b) use ($sortby) { + return strnatcmp($a[$sortby], $b[$sortby]); + }); + + return $links[$view][$nav_name]; + else: + return false; + endif; + + } + + public static function getGroupNavigation($group_name, $sortby ='order') { + + $links = array(); + + $service = owa_coreAPI::serviceSingleton(); + + foreach ($service->modules as $k => $v) { + + // If the module does not have nav links, register them. needed in case this function is called twice on + // same view. + if ( empty( $v->nav_links ) ) { + + $v->registerNavigation(); + } + + $module_nav = $v->getNavigationLinks(); + + if ( $module_nav ) { + + //loop through returned nav array + foreach ( $module_nav as $group => $nav_links ) { + + foreach ( $nav_links as $subgroup => $link ) { + + // check to see if group exists + if ( array_key_exists( $group, $links ) ) { + + // check to see if subgroup is already present in the main array + if ( array_key_exists( $subgroup, $links[ $group ] ) ) { + // merge various elements?? not now. + + //check to see if there is an existing set of subgroup links + if ( array_key_exists( 'subgroup', $links[ $group ][ $subgroup ] ) ) { + // if so, merge the subgroups + $links[ $group ][ $subgroup ][ 'subgroup' ] = array_merge( $links[ $group ][ $subgroup ][ 'subgroup' ], $link[ 'subgroup' ] ); + } else { + + } + } else { + // else populate the link + $links[$group][$subgroup] = $link; + } + + } else { + $links[$group][$subgroup] = $link; + } + } + + } + } + } + + if ( isset( $links[$group_name] ) ) { + + return $links[$group_name]; + } + } + + /** + * @Todo REMOVE + */ + public static function getNavSort($a, $b) { + + return strnatcmp($a['order'], $b['order']); + } + + + public static function getActiveModules() { + + $c = owa_coreAPI::configSingleton(); + + $config = $c->config->get('settings'); + + + $active_modules = array(); + + foreach ($config as $k => $module) { + + if ( isset($module['is_active']) && $module['is_active'] == true) { + $active_modules[] = $k; + } + } + + return $active_modules; + + } + + public static function getModulesNeedingUpdates() { + + $service = owa_coreAPI::serviceSingleton(); + + return $service->getModulesNeedingUpdates(); + } + + /** + * Invokes controller to perform controller + * + * @param $action string + * + */ + public static function performAction($action, $params = array()) { + + // Load action from service map + $service = owa_coreAPI::serviceSingleton(); + $action_map = $service->getMapValue('actions', $action ); + + // create the controller object + if ( $action_map ) { + $controller = owa_lib::simpleFactory( $action_map['class_name'], $action_map['file'], $params ); + } else { + // attempt to use old style convention + $controller = owa_coreAPI::moduleFactory($action, 'Controller', $params); + } + + if ( ! $controller || ! method_exists( $controller, 'doAction' ) ) { + + owa_coreAPI::debug("No controller is associated with $action."); + return; + } + + // call the doAction method which is part of the abstract controller class + // inherited by all other controller classes + $data = $controller->doAction(); + + // Display view if controller calls for one. + if ( ! empty( $data['view'] ) || ! empty( $data['action'] ) ) { + + // Redirect to a view + if ( $data['view_method'] == 'redirect' ) { + + return owa_lib::redirectToView( $data ); + + // return an image . Will output headers and binary data. + } elseif ( $data['view_method'] == 'image' ) { + + return owa_coreAPI::displayImage( $data ); + + } else { + + return owa_coreAPI::displayView( $data ); + } + + } elseif( ! empty( $data['do'] ) ) { + + return owa_lib::redirectToView( $data ); + } + } + + /** + * Logs an event to the event queue + * + * take an owa_event object as a message. + * + * @param string $event_type + * @param object $message + * @return boolean + */ + public static function logEvent($event_type, $message = '') { + + // debug + owa_coreAPI::debug("logging event $event_type"); + + if (owa_coreAPI::getSetting('base', 'error_log_level') > 9) { + owa_coreAPI::debug("PHP Server Global: ".print_r($_SERVER, true)); + } + + // Check to see if named users should be logged + if (owa_coreAPI::getSetting('base', 'log_named_users') != true) { + $cu = owa_coreAPI::getCurrentUser(); + $cu_user_id = $cu->getUserData('user_id'); + + if(!empty($cu_user_id)) { + return false; + } + } + + // do not log if the request is robotic + $service = owa_coreAPI::serviceSingleton(); + $bcap = $service->getBrowscap(); + owa_coreAPI::profile(__CLASS__, __FUNCTION__, __LINE__); + if (!owa_coreAPI::getSetting('base', 'log_robots')) { + + if ($bcap->robotCheck()) { + owa_coreAPI::debug("ABORTING: request appears to be from a robot"); + owa_coreAPI::setRequestParam('is_robot', true); + return; + } + owa_coreAPI::profile(__CLASS__, __FUNCTION__, __LINE__); + } + + // form event if one was not passed + $class= 'owa_event'; + if (!($message instanceof $class)) { + $event = owa_coreAPI::supportClassFactory('base', 'event'); + $event->setProperties($message); + $event->setEventType($event_type); + } else { + $event = $message; + } + + // STAGE 1 - set environmental properties from SERVER + $teh = owa_coreAPI::getInstance( 'owa_trackingEventHelpers', OWA_BASE_CLASS_DIR.'trackingEventHelpers.php'); + $environmentals = $service->getMap( 'tracking_properties_environmental' ); + $teh->setTrackerProperties( $event, $environmentals ); + + // Filter XSS exploits from event properties + //$event->cleanProperties(); + + // do not log if the do not log property is set on the event. + if ($event->get('do_not_log')) { + return false; + } + + // check to see if IP should be excluded + if ( owa_coreAPI::isIpAddressExcluded( $event->get('ip_address') ) ) { + owa_coreAPI::debug("Not logging event. IP address found in exclusion list."); + return false; + } + + // queue for later or process event straight away + if ( owa_coreAPI::getSetting( 'base', 'queue_events' ) || + owa_coreAPI::getSetting( 'base', 'queue_incoming_tracking_events' ) ) { + + $q = owa_coreAPI::getEventQueue( 'incoming_tracking_events' ); + owa_coreAPI::debug('Queuing '.$event->getEventType().' event with properties: '.print_r($event->getProperties(), true ) ); + $q->sendMessage( $event ); + + } else { + + // lookup which event processor to use to process this event type + $processor_action = owa_coreAPI::getEventProcessor( $event->getEventType() ); + return owa_coreAPI::handleRequest( array( 'event' => $event ), $processor_action ); + } + } + + public static function getInstance( $class, $path ) { + + if ( ! class_exists( $class ) ) { + + require_once( $path ); + } + + return $class::getInstance(); + } + + public static function displayImage($data) { + + header('Content-type: image/gif'); + header('P3P: CP="'.owa_coreAPI::getSetting('base', 'p3p_policy').'"'); + header('Expires: Sat, 22 Apr 1978 02:19:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + header('Cache-Control: no-store, no-cache, must-revalidate'); + header('Pragma: no-cache'); + + echo owa_coreAPI::displayView($data); + } + + + /** + * Displays a View without user authentication. Takes array of data as input + * + * @param array $data + * @param string $viewfile a specific view file to use + * @return string + * + */ + public static function displayView($data, $viewfile = '') { + + if (empty($viewfile)): + $viewfile = $data['view']; + endif; + + $view = owa_coreAPI::moduleFactory($viewfile, 'View'); + $view->setData($data); + return $view->assembleView($data); + + } + + public static function displaySubView($data, $viewfile = '') { + + if (empty($viewfile)): + $viewfile = $data['view']; + endif; + + $view = owa_coreAPI::subViewFactory($viewfile); + + return $view->assembleView($data); + + } + + /** + * Strip a URL of certain GET params + * @depricated + * @return string + * @todo REMOVE + */ + function stripDocumentUrl($url) { + + if (owa_coreAPI::getSetting('base', 'clean_query_string')): + + if (owa_coreAPI::getSetting('base', 'query_string_filters')): + $filters = str_replace(' ', '', owa_coreAPI::getSetting('base', 'query_string_filters')); + $filters = explode(',', $filters); + else: + $filters = array(); + endif; + + // OWA specific params to filter + array_push($filters, owa_coreAPI::getSetting('base', 'source_param')); + array_push($filters, owa_coreAPI::getSetting('base', 'ns').owa_coreAPI::getSetting('base', 'feed_subscription_param')); + + //print_r($filters); + + foreach ($filters as $filter => $value) { + + $url = preg_replace( + '#\?' . + $value . + '=.*$|&' . + $value . + '=.*$|' . + $value . + '=.*&#msiU', + '', + $url + ); + + } + + endif; + //print $url; + + return $url; + + } + + public static function getRequestParam($name) { + + $service = owa_coreAPI::serviceSingleton(); + + return $service->request->getParam($name); + + } + + public static function getRequest() { + $service = owa_coreAPI::serviceSingleton(); + return $service->request; + } + + public static function setRequestParam($name, $value) { + + $service = owa_coreAPI::serviceSingleton(); + return $service->request->setParam($name, $value); + + } + + public static function makeTimePeriod($time_period, $params = array()) { + + $period = owa_coreAPI::supportClassFactory('base', 'timePeriod'); + + if ( ! array_key_exists('period', $params)) { + $params['period'] = $time_period; + } + $period->setFromMap( $params ); + return $period; + } + + /** + * Factory method for producing validation objects + * + * @return Object + */ + public static function validationFactory($class_file) { + + if (!class_exists('owa_validation')): + require_once(OWA_BASE_CLASS_DIR.'validation.php'); + endif; + + return owa_lib::factory(OWA_PLUGIN_DIR.'validations', 'owa_', $class_file, array(), 'Validation'); + + } + + public static function debug($msg) { + + $e = owa_coreAPI::errorSingleton(); + $e->debug($msg); + return; + } + + public static function error($msg) { + + $e = owa_coreAPI::errorSingleton(); + $e->err($msg); + return; + } + + public static function notice($msg) { + + $e = owa_coreAPI::errorSingleton(); + $e->notice($msg); + return; + } + + public static function createCookie($cookie_name, $cookie_value, $expires = 0, $path = '/', $domain = '') { + + if ( $domain ) { + // sanitizes the domain + $domain = owa_lib::sanitizeCookieDomain( $domain ); + } else { + $domain = owa_coreAPI::getSetting('base', 'cookie_domain'); + } + if (is_array($cookie_value)) { + + $cookie_value = owa_lib::implode_assoc('=>', '|||', $cookie_value); + } + + // add namespace + $cookie_name = sprintf('%s%s', owa_coreAPI::getSetting('base', 'ns'), $cookie_name); + + // debug + owa_coreAPI::debug(sprintf('Setting cookie %s with values: %s under domain: %s', $cookie_name, $cookie_value, $domain)); + + // makes cookie to session cookie only + if (!owa_coreAPI::getSetting('base', 'cookie_persistence')) { + $expires = 0; + } + + // set compact privacy header + header(sprintf('P3P: CP="%s"', owa_coreAPI::getSetting('base', 'p3p_policy'))); + //owa_coreAPI::debug('time: '.$expires); + setcookie($cookie_name, $cookie_value, $expires, $path, $domain); + return; + } + + public static function deleteCookie($cookie_name, $path = '/', $domain = '') { + + return owa_coreAPI::createCookie($cookie_name, false, time()-3600*25, $path, $domain); + } + + public static function registerStateStore($name, $expiration, $length = '', $format = '', $type = 'cookie', $cdh_required = '') { + + $service = owa_coreAPI::serviceSingleton(); + return $service->request->state->registerStore( $name, $expiration, $length, $format, $type, $cdh_required ); + } + + public static function setState($store, $name = '', $value, $store_type = '', $is_perminent = '') { + + $service = owa_coreAPI::serviceSingleton(); + return $service->request->state->set($store, $name, $value, $store_type, $is_perminent); + } + + public static function getState($store, $name = '') { + + $service = owa_coreAPI::serviceSingleton(); + return $service->request->state->get($store, $name); + } + + // depricated + public static function getStateParam($store, $name = '') { + + return owa_coreAPI::getState($store, $name); + } + + public static function getServerParam($name = '') { + + $service = owa_coreAPI::serviceSingleton(); + return $service->request->getServerParam($name); + } + + public static function clearState($store, $name = '') { + + $service = owa_coreAPI::serviceSingleton(); + $service->request->state->clear($store, $name); + + } + + public static function getEventProcessor($event_type) { + + $service = owa_coreAPI::serviceSingleton(); + $processor = $service->getMapValue('event_processors', $event_type); + + if (empty($processor)) { + + $processor = 'base.processEvent'; + } + + return $processor; + } + + /** + * Retrieves any registered build packages + * + * @return array + */ + public static function getBuildPackages() { + + $service = owa_coreAPI::serviceSingleton(); + $map = $service->getMap('build_packages'); + + if ( ! $map ) { + $map = array(); + } + + return $map; + } + + /** + * Handles OWA internal page/action requests + * + * @return unknown + */ + public static function handleRequest($caller_params = null, $action = '') { + + static $init; + + $service = owa_coreAPI::serviceSingleton(); + // Override request parsms with those passed by caller + if (!empty($caller_params)) { + $service->request->mergeParams($caller_params); + }; + + $params = $service->request->getAllOwaParams(); + + if ($init != true) { + owa_coreAPI::debug('Handling request with params: '. print_r($params, true)); + } + + // backwards compatability with old style view/controler scheme + // still needed?? + if (array_key_exists('view', $params)) { + // its a view request so the only data is in whats in the params + $init = true; + return owa_coreAPI::displayView($params); + } + + if (empty($action)) { + $action = owa_coreAPI::getRequestParam('action'); + if (empty($action)) { + $action = owa_coreAPI::getRequestParam('do'); + + if (empty($action)) { + $action = owa_coreAPI::getSetting('base', 'start_page'); + $params['do'] = $action; + } + } + } + + $init = true; + owa_coreAPI::debug('About to perform action: '.$action); + return owa_coreAPI::performAction($action, $params); + + } + + public static function isUpdateRequired() { + + $service = owa_coreAPI::serviceSingleton(); + return $service->isUpdateRequired(); + } + + /** + * @return array + */ + public static function getSitesList() { + $db = owa_coreAPI::dbSingleton(); + $db->selectFrom('owa_site'); + $db->selectColumn('*'); + $sites = $db->getAllRows(); + + if ( ! $sites ) { + $sites = array(); + } + return $sites; + } + + public static function profile($that = '', $function = '', $line = '', $msg = '') { + + if (defined('OWA_PROFILER')) { + if (OWA_PROFILER === true) { + + static $profiler; + + if (!class_exists('PhpQuickProfiler')) { + require_once(OWA_INCLUDE_DIR.'pqp/classes/PhpQuickProfiler.php'); + } + + if (empty($profiler)) { + $profiler = new PhpQuickProfiler(PhpQuickProfiler::getMicroTime(), OWA_INCLUDE_DIR.'pqp/'); + } + + $class = get_class($that); + Console::logSpeed($class."::$function - Line: $line - Msg: $msg"); + Console::logMemory($that, $class. "::$function - Line: $line"); + + return $profiler; + } + } + } + + public static function profileDisplay() { + $p = owa_coreAPI::profile(); + if ($p) { + $p->display(); + } + + } + + public static function getEventDispatch() { + + if (! class_exists( 'owa_eventDispatch' ) ) { + require_once(OWA_BASE_CLASS_DIR.'eventDispatch.php'); + } + + return owa_eventDispatch::get_instance(); + + } + + public static function getEventQueue( $name ) { + + static $queues; + + // make queue if needed + if ( ! isset( $queues[ $name ] ) ) { + + // get queue config + $s = owa_coreAPI::serviceSingleton(); + $map = $s->getMapValue('event_queues', $name); + + if ( $map ) { + + $implementation = $s->getMapValue( 'event_queue_types', $map['queue_type'] ); + + if ( $implementation + && isset( $implementation[0] ) + && isset( $implementation[1] ) + ) { + owa_coreAPI::debug(print_r($implementation, true)); + $queues[ $name ] = owa_lib::simpleFactory( $implementation[0], $implementation[1], $map ); + + } else { + + throw new Exception("No event queue by that type found."); + } + + } else { + + throw new Exception("No configuration found for event queue $name."); + } + } + // return queue + return $queues[ $name ]; + } + + public static function getCliCommandClass($command) { + + $s = owa_coreAPI::serviceSingleton(); + return $s->getCliCommandClass($command); + } + + public static function getGeolocationFromIpAddress($ip_address) { + + $s = owa_coreAPI::serviceSingleton(); + $s->geolocation->getGeolocationFromIp($ip_address); + return $s->geolocation; + } + + public static function getNonceTimeInterval() { + + return ceil( time() / owa_coreAPI::getSetting( 'base', 'nonce_expiration_period') ); + } + + public static function createNonce($action) { + + $time = owa_coreAPI::getNonceTimeInterval(); + $cu = owa_coreAPI::getCurrentUser(); + $user_id = $cu->getUserData( 'user_id' ); + + $full_nonce = $time . $action . $user_id . 'owa_nonce'; + + $nonce = substr( owa_coreAPI::saltedHash($full_nonce, 'nonce'), -12, 10); + + return $nonce; + } + + public static function saltedHash( $data, $scheme, $hash_type = 'md5' ) { + + $salt = owa_coreAPI::getSalt( $scheme ); + return owa_lib::hash( $hash_type, $data, $salt ); + } + + + + public static function getSalt( $scheme ) { + + static $cached_salts; + + $scheme = strtoupper($scheme); + + if ( ! $cached_salts ) { + + $cached_salts = array(); + $ns = strtoupper( owa_coreAPI::getSetting('base', 'ns') ); + + foreach (array('NONCE', 'SECRET', 'AUTH') as $f ) { + + foreach (array('KEY', 'SALT') as $s ) { + + $const = sprintf("%s%s_%s", $ns, $f, $s); + + if ( ! defined ( "$const" ) ) { + continue; + } else { + + $cached_salts[ $f.'_'.$s ] = constant("$const"); + } + } + } + } + + + $key = ''; + $salt = ''; + + if (array_key_exists( $scheme.'_KEY', $cached_salts ) ) { + + $key = $cached_salts[ $scheme.'_KEY' ]; + } + + if (array_key_exists( $scheme.'_SALT', $cached_salts ) ) { + + $salt = $cached_salts[ $scheme.'_SALT' ]; + } + + return $key . $salt; + } + + public static function secureRandomString( $length, $special_chars = true, $more_special_chars = true ) { + + $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + if ( $special_chars ) + $chars .= '!@#$%^&*()'; + if ( $more_special_chars ) + $chars .= '-_ []{}<>~`+=,.;:/?|'; + + $password = ''; + for ( $i = 0; $i < $length; $i++ ) { + $password .= substr($chars, owa_coreAPI::random(0, strlen($chars) - 1), 1); + } + + return $password; + } + + public static function random($min, $max) { + + static $rnd_value; + + if ( strlen($rnd_value) < 8 ) { + + $notrandom = false; + + if ( function_exists( 'openssl_random_pseudo_bytes' ) ) { + + $rnd_value = bin2hex(openssl_random_pseudo_bytes(32, $cstrong)); + + if ( ! $cstrong ) { + + $notrandom = true; + } + + } else { + + $notrandom = true; + } + + if ( $notrandom ) { + + $seed = microtime(); + $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed ); + $rnd_value .= sha1($rnd_value); + $rnd_value .= sha1($rnd_value . $seed); + + } + + //$seed = md5($seed . $rnd_value); + } + // Take the first 8 digits for our value + $value = substr($rnd_value, 0, 8); + + // Strip the first eight, leaving the remainder for the next call to random. + $rnd_value = substr($rnd_value, 8); + + $value = abs(hexdec($value)); + + // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats. + $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff + + // Reduce the value to be within the min - max range + if ( $max != 0 ) + $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 ); + + return abs(intval($value)); + } + + public static function summarize($map) { + + $entity = owa_coreAPI::entityFactory($map['entity']); + $db = owa_coreAPI::dbSingleton(); + $db->selectFrom($entity->getTableName(), $entity->getTableAlias()); + + foreach ($map['columns'] as $col => $action) { + + switch ($action) { + + case 'sum': + $col_def = sprintf("SUM(%s)", $col); + $name = $col.'_sum'; + break; + case 'count': + $col_def = sprintf("COUNT(%s)", $col); + $name = $col.'_count'; + break; + case 'count_distinct': + $col_def = sprintf("COUNT(distinct %s)", $col); + $name = $col.'_dcount'; + break; + case 'max': + $col_def = sprintf("MAX(%s)", $col); + $name = $col.'_max'; + break; + } + + $db->selectColumn($col_def, $name); + } + + foreach ($map['constraints'] as $con_col => $con_value) { + + if ( is_array( $con_value ) ) { + $db->where($con_col, $con_value['value'], $con_value['operator']); + } else { + $db->where($con_col, $con_value); + } + } + + $ret = $db->getOneRow(); + return $ret; + } + + public static function getJsTrackerTag( $site_id, $options = array() ) { + + if ( ! class_exists( 'owa_template' ) ) { + require_once(OWA_BASE_CLASSES_DIR.'owa_template.php'); + } + + $t = new owa_template(); + + if (owa_coreAPI::getSetting('base', 'is_embedded')) { + + // needed to override the endpoint used by the js tracker + $options['apiEndpoint'] = owa_coreAPI::getSetting('base', 'api_url'); + } + + $t->set( 'site_id', $site_id ); + $cmds = owa_coreAPI::filter( 'tracker_tag_cmds', array() ); + $t->set( 'cmds', $cmds ); + $t->set('options', $options); + $t->set_template('js_log_tag.tpl'); + return $t->fetch(); + } + + public static function activateModule( $module_name ) { + + if ( $module_name ) { + + $m = owa_coreAPI::moduleClassFactory($module_name); + return $m->activate(); + } + } + + public static function deactivateModule( $module_name ) { + + if ( $module_name ) { + + $s = owa_coreAPI::serviceSingleton(); + $m = $s->getModule($module_name); + return $m->deactivate(); + } + } + + public static function installModule( $module_name ) { + + if ($module_name) { + + $m = owa_coreAPI::moduleClassFactory($module_name); + $status = $m->install(); + return $status; + } + } + + public static function generateInstanceSpecificHash() { + + if ( defined( 'OWA_SECRET' ) ) { + $salt = OWA_SECRET; + } else { + $salt = ''; + } + + if ( defined( 'OWA_DB_USER' ) ) { + $salt .= OWA_DB_USER; + } + + if ( defined( 'OWA_DB_PASSWORD' ) ) { + $salt .= OWA_DB_PASSWORD; + } + + return md5( $salt ); + } + + public static function getAllDimensions() { + + $s = owa_coreAPI::serviceSingleton(); + + $dims = $s->dimensions; + + foreach ( $s->denormalizedDimensions as $k => $entity_dims ) { + foreach ($entity_dims as $entity => $dedim) { + $dims[$k] = $dedim; + } + } + + return $dims; + } + + public static function getAllMetrics() { + + $s = owa_coreAPI::serviceSingleton(); + return $s->metrics; + } + + public static function getGoalManager( $siteId ) { + + static $gm; + + if ( ! $gm ) { + + $gm = array(); + } + + if ( ! isset( $gm[$siteId] ) ) { + $gm[ $siteId ] = owa_coreAPI::supportClassFactory('base', 'goalManager', $siteId); + } + + return $gm[$siteId]; + } + + public static function getRequestTimestamp() { + + $r = owa_coreAPI::requestContainerSingleton(); + return $r->getTimestamp(); + } + + public static function isEveryoneCapable( $capability ) { + + $caps = owa_coreAPI::getCapabilities('everyone'); + + if ( in_array( $capability, $caps ) ) { + return true; + } else { + return false; + } + } + + public static function getCurrentUrl() { + $r = owa_coreAPI::requestContainerSingleton(); + return $r->getCurrentUrl(); + } + + public static function isIpAddressExcluded( $ip_address ) { + + // do not log if ip address is on the do not log list + $ips = owa_coreAPI::getSetting( 'base', 'excluded_ips' ); + owa_coreAPI::debug('excluded ips: '.$ips); + if ( $ips ) { + + $ips = trim( $ips ); + + if ( strpos( $ips, ',' ) ) { + $ips = explode( ',', $ips ); + } else { + $ips = array( $ips ); + } + + foreach( $ips as $ip ) { + $ip = trim( $ip ); + if ( $ip_address === $ip ) { + owa_coreAPI::debug("Request is from excluded ip address: $ip."); + return true; + } + } + } + } + + /** + * Attaches an event handler to the event queue + * + * @param array $event_name + * @param string $handler_name + * @return boolean + */ + public static function registerFilter( $filter_name, $callback, $priority = 10 ) { + + $ed = owa_coreAPI::getEventDispatch(); + $ed->attachFilter($filter_name, $callback, $priority); + } + + public static function filter( $filter_name, $value ) { + + $ed = owa_coreAPI::getEventDispatch(); + return $ed->filter( $filter_name, $value ); + } + +} + ?> \ No newline at end of file diff --git a/owa_db.php b/owa_db.php index de6529c8b..02acb1de7 100644 --- a/owa_db.php +++ b/owa_db.php @@ -1,1146 +1,1146 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_db extends owa_base { - - /** - * Database Connection - * - * @var object - */ - var $connection; - - var $connectionParams; - - /** - * Number of queries - * - * @var integer - */ - var $num_queries; - - /** - * Raw result object - * - * @var object - */ - var $new_result; - - /** - * Rows - * - * @var array - */ - var $result; - - /** - * Caller Params - * - * @var array - */ - var $params = array(); - - /** - * Status of selecting a databse - * - * @var boolean - */ - var $database_selection; - - /** - * Status of connection - * - * @var boolean - */ - var $connection_status; - - /** - * Number of rows in result set - * - * @var integer - */ - var $num_rows; - - /** - * Number of rows affected by insert/update/delete statements - * - * @var integer - */ - var $rows_affected; - - /** - * Microtime Start of Query - * - * @var unknown_type - */ - var $_start_time; - - /** - * Total Elapsed time of query - * - * @var unknown_type - */ - var $_total_time; - - /** - * Storage Array for components of sql queries - * - * @var array - */ - var $_sqlParams = array(); - - /** - * Sql Statement - * - * @var string - */ - var $_sql_statement; - - /** - * Last Sql Statement - * - * @var string - */ - var $_last_sql_statement; - - function __construct($db_host, $db_port, $db_name, $db_user, $db_password, $open_new_connection = true, $persistant = false) { - - $this->connectionParams = array('host' => $db_host, - 'port' => $db_port, - 'user' => $db_user, - 'password' => $db_password, - 'name' => $db_name, - 'open_new_connection' => $open_new_connection, - 'persistant' => $persistant); - - return parent::__construct(); - } - - function __destruct() { - - if ( $this->isConnectionEstablished() ) { - - $this->close(); - } - } - - function connect() { - - - return false; - } - - function pconnect() { - - return false; - } - - function close() { - - return false; - } - - function isConnectionEstablished() { - - return $this->connection_status; - } - - function getConnectionParam($name) { - - if (array_key_exists($name, $this->connectionParams)) { - return $this->connectionParams[$name]; - } - } - - /** - * Prepare string - * - * @param string $string - * @return string - */ - function prepare_string($string) { - - $chars = array("\t", "\n"); - return str_replace($chars, " ", $string); - } - - /** - * Starts the query microtimer - * - */ - function _timerStart() { - - $mtime = microtime(); - //$mtime = explode(' ', $mtime); - //$this->_start_time = $mtime[1].substr(round($mtime[0], 4), 1); - $this->_start_time = microtime(); - return; - } - - /** - * Ends the query microtimer and populates $this->_total_time - * - */ - function _timerEnd() { - - $mtime = microtime(); - //$mtime = explode(" ", $mtime); - //$endtime = $mtime[1].substr(round($mtime[0], 4), 1); - $endtime = microtime(); - //$this->_total_time = bcsub($endtime, $this->_start_time, 4); - $this->_total_time = number_format(((substr($endtime,0,9)) + (substr($endtime,-10)) - (substr($this->_start_time,0,9)) - (substr($this->_start_time,-10))),6); - - return; - - } - - function selectColumn($name, $as = '') { - - if (is_array($name)) { - $as = $name[1]; - $name = $name[0]; - } - - $this->_sqlParams['select_values'][] = array('name' => $name, 'as' => $as); - - return; - } - - function select($name, $as = '') { - return $this->selectColumn($name, $as = ''); - } - - function where($name, $value, $operator = '=') { - - if ( ! owa_lib::isEmpty( $value ) ) { - - // hack for intentional empty value - if($value == ' '){ - $value = ''; - } - - $this->_sqlParams['where'][$name] = array('name' => $name, 'value' => $value, 'operator' => $operator); - } - } - - function having($name, $value, $operator = '=') { - - if ( ! owa_lib::isEmpty( $value ) ) { - - // hack for intentional empty value - if($value == ' ') { - $value = ''; - } - - $this->_sqlParams['having'][$name] = array('name' => $name, 'value' => $value, 'operator' => $operator); - } - } - - function multiWhere($where_array = array()) { - - if (!empty($where_array)): - - foreach ($where_array as $k => $v) { - if ( ! owa_lib::isEmpty($v) ): - - if (empty($v['operator'])): - $v['operator'] = '='; - endif; - - $this->_sqlParams['where'][$k] = array('name' => $k, 'value' => $v['value'], 'operator' => $v['operator']); - endif; - } - - endif; - } - - function groupBy($col) { - - $this->_sqlParams['groupby'][] = $col; - return; - } - - function orderBy($col, $flag = '') { - - $this->_sqlParams['orderby'][] = array($col, $flag); - return; - } - - function order($flag) { - - $this->_sqlParams['order'] = $flag; - return; - } - - function limit($value) { - - $this->_sqlParams['limit'] = $value; - return; - } - - function offset($value) { - - $this->_sqlParams['offset'] = $value; - return; - } - - function set($name, $value) { - - $this->_sqlParams['set_values'][] = array('name' => $name, 'value' => $value); - return; - } - - function executeQuery() { - - switch($this->_sqlParams['query_type']) { - - case 'insert': - - return $this->_insertQuery(); - - case 'select': - - return $this->_selectQuery(); - - case 'update': - - return $this->_updateQuery(); - - case 'delete': - - return $this->_deleteQuery(); - - default: - - return $this->_query(); - } - } - - function getAllRows() { - - return $this->_selectQuery(); - } - - function getOneRow() { - - $this->limit(1); - $ret = $this->_selectQuery(); - return $ret[0]; - } - - function _setSql($sql) { - $this->_sql_statement = $sql; - } - - function selectFrom($name, $as = '') { - - if (is_array($name)) { - $as = $name[1]; - $name = $name[0]; - } - - $this->_sqlParams['query_type'] = 'select'; - $this->_sqlParams['from'][$name] = array('name' => $name, 'as' => $as); - } - - function from( $name, $as = '' ) { - - return $this->selectFrom( $name, $as ); - } - - function insertInto($table) { - - $this->_sqlParams['query_type'] = 'insert'; - $this->_sqlParams['table'] = $table; - } - - function deleteFrom($table) { - - $this->_sqlParams['query_type'] = 'delete'; - $this->_sqlParams['table'] = $table; - } - - function updateTable($table) { - - $this->_sqlParams['query_type'] = 'update'; - $this->_sqlParams['table'] = $table; - } - - function _insertQuery() { - owa_coreAPI::profile($this, __FUNCTION__, __LINE__); - $params = $this->_fetchSqlParams('set_values'); - - $count = count($params); - - $i = 0; - - $sql_cols = ''; - $sql_values = ''; - - foreach ($params as $k => $v) { - - $sql_cols .= $v['name']; - $sql_values .= "'".$this->prepare($v['value'])."'"; - - $i++; - - // Add commas - if ($i < $count): - - $sql_cols .= ", "; - $sql_values .= ", "; - - endif; - } - owa_coreAPI::profile($this, __FUNCTION__, __LINE__); - $this->_setSql(sprintf(OWA_SQL_INSERT_ROW, $this->_sqlParams['table'], $sql_cols, $sql_values)); - owa_coreAPI::profile($this, __FUNCTION__, __LINE__); - $ret = $this->_query(); - owa_coreAPI::profile($this, __FUNCTION__, __LINE__); - return $ret; - - } - - function generateSelectQuerySql() { - - $cols = ''; - $i = 0; - $params = $this->_fetchSqlParams('select_values'); - $count = count($params); - - foreach ($params as $k => $v) { - - $cols .= $v['name']; - - // Add as - if (!empty($v['as'])): - - $cols .= ' as '.$v['as']; - - endif; - - // Add commas - if ($i < $count - 1): - - $cols .= ', '; - - endif; - - $i++; - - } - - $sql = sprintf("SELECT %s FROM %s %s %s %s %s %s", - $cols, - $this->_makeFromClause(), - $this->_makeWhereClause(), - $this->_makeGroupByClause(), - $this->_makeHavingClause(), - $this->_makeOrderByClause(), - $this->_makeLimitClause() - ); - $this->_setSql($sql); - return $sql; - } - - function _selectQuery() { - - $this->generateSelectQuerySql(); - return $this->_query(); - - } - - - function _updateQuery() { - - $params = $this->_fetchSqlParams('set_values'); - - $count = count($params); - - $i = 0; - - $sql_cols = ''; - $sql_values = ''; - $set = ''; - - foreach ($params as $k => $v) { - - //$sql_cols = $sql_cols.$key; - //$sql_values = $sql_values."'".$this->prepare($value)."'"; - - // Add commas - if ($i != 0): - - $set .= ', '; - - endif; - - $set .= $v['name'] .' = \'' . $this->prepare($v['value']) . '\''; - - $i++; - } - - $this->_setSql(sprintf(OWA_SQL_UPDATE_ROW, $this->_sqlParams['table'], $set, $this->_makeWhereClause())); - - return $this->_query(); - } - - function _deleteQuery() { - - $this->_setSql(sprintf(OWA_SQL_DELETE_ROW, $this->_sqlParams['table'], $this->_makeWhereClause())); - - return $this->_query(); - } - - function rawQuery($sql) { - - $this->_setSql($sql); - - return $this->_query(); - } - - function _fetchSqlParams($sql_params_name) { - - if (array_key_exists($sql_params_name, $this->_sqlParams)): - if (!empty($this->_sqlParams[$sql_params_name])): - return $this->_sqlParams[$sql_params_name]; - else: - return false; - endif; - else: - return false; - endif; - } - - function _makeWhereClause() { - - $params = $this->_fetchSqlParams('where'); - - if ( ! empty( $params ) ) { - - return $this->_makeConstraintClause('WHERE', $params); - } - } - - function _makeHavingClause() { - - $params = $this->_fetchSqlParams('having'); - - if ( ! empty( $params ) ) { - - return $this->_makeConstraintClause('HAVING', $params); - } - } - - function _makeConstraintClause($type = 'WHERE', $params) { - - if ( ! empty( $params ) ) { - - $count = count( $params ); - $i = 0; - - $constraint = $type.' '; - - foreach ($params as $k => $v) { - - switch (strtolower($v['operator'])) { - - case '==': - $constraint .= sprintf("%s = '%s'",$v['name'], $this->prepare( $v['value'] ) ); - break; - - case 'between': - $constraint .= sprintf("%s BETWEEN '%s' AND '%s'", $v['name'], $this->prepare( $v['value']['start'] ), $this->prepare( $v['value']['end'] ) ); - break; - - case '=~': - $constraint .= sprintf("%s %s '%s'",$v['name'], OWA_SQL_REGEXP, $this->prepare( $v['value'] ) ); - break; - - case '!~': - $constraint .= sprintf("%s %s '%s'",$v['name'], OWA_SQL_NOTREGEXP, $this->prepare( $v['value'] ) ); - break; - - case '=@': - $constraint .= sprintf("LOCATE('%s', %s) > 0",$v['value'], $this->prepare( $v['name'] ) ); - break; - - case '!@': - $constraint .= sprintf("LOCATE('%s', %s) = 0",$v['value'], $this->prepare( $v['name'] ) ); - break; - - default: - $constraint .= sprintf("%s %s '%s'",$v['name'], $v['operator'], $this->prepare( $v['value'] ) ); - break; - } - - if ($i < $count - 1) { - - $constraint .= " AND "; - } - - $i++; - } - - return $constraint; - } - } - - function join($type, $table, $as, $foreign_key, $primary_key = '') { - - if (!$primary_key) { - - if (!$as) { - $as = $table; - } - - $primary_key = $as.'.id'; - } - - - - $this->_sqlParams['joins'][$as] = array('type' => $type, - 'table' => $table, - 'as' => $as, - 'foreign_key' => $foreign_key, - 'primary_key' => $primary_key); - - } - - function prepare ( $string ) { - - return $string; - } - - function _makeJoinClause() { - - $params = $this->_fetchSqlParams('joins'); - - if (!empty($params)): - - $join_clause = ''; - - foreach ($params as $k => $v) { - - if (!empty($v['as'])): - $join_clause .= sprintf(" %s %s AS %s ON %s = %s", $v['type'], - $v['table'], - $v['as'], - $v['foreign_key'], - $v['primary_key']); - else: - $join_clause .= sprintf(" %s %s ON %s = %s", $v['type'], - $v['table'], $v['foreign_key'], - $v['primary_key']); - endif; - - - - } - - return $join_clause; - - else: - return; - endif; - - } - - function _makeFromClause() { - - $from = ''; - $i = 0; - $params = $this->_fetchSqlParams('from'); - - if(!empty($params)): - - $count = count($params); - - foreach ($params as $k => $v) { - - $from .= $v['name']; - - // Add as - if (!empty($v['as'])): - - $from .= ' as '.$v['as']; - - endif; - - // Add commas - if ($i < $count - 1): - - $from .= ', '; - - endif; - - $i++; - - } - - $from .= $this->_makeJoinClause(); - - return $from; - else: - $this->e->debug("No SQL FROM params set."); - return false; - endif; - - } - - function _makeGroupByClause() { - - $params = $this->_fetchSqlParams('groupby'); - - if (!empty($params)): - - return sprintf("GROUP BY %s", $this->_makeDelimitedValueList($params)); - - else: - return; - endif; - - - } - - function _makeOrderByClause() { - - $sorts = $this->_fetchSqlParams('orderby'); - //print_r($sorts); - if (!empty($sorts)): - - $order = $this->_fetchSqlParams('order'); - - $i = 1; - $sort_string = ''; - $count = count($sorts); - foreach ($sorts as $sort) { - - // needed for backwards compatability. - if (!isset($sort[1])) { - $sort[1] = $order; - } - - $sort_string .= sprintf("%s %s",$sort[0], $sort[1]); - if ($i < $count) { - $sort_string .= ', '; - } - - $i++; - } - - return sprintf("ORDER BY %s", $sort_string); - - else: - return; - endif; - - - } - - function _makeLimitClause() { - - $param = $this->_fetchSqlParams('limit'); - - if(!empty($param)): - $limit = sprintf("LIMIT %d", $param); - - $offset = $this->_makeOffsetClause(); - - $ret = $limit . ' ' . $offset; - - return $ret; - else: - return; - endif; - - } - - function _makeOffsetClause() { - - $param = $this->_fetchSqlParams('offset'); - - if(!empty($param)): - return sprintf("OFFSET %d", $param); - else: - return; - endif; - - } - - - /** - * Creates a delimited value list from an array or arrays. - * - */ - function _makeDelimitedValueListArray($values, $delimiter = ', ', $inner_delimiter = ' ') { - - $items = ''; - $i = 0; - $count = count($values); - - //print_r($values); - - foreach ($values as $k) { - - $items .= implode($inner_delimiter, $k); - - // Add commas - if ($i < $count - 1): - - $items .= $delimiter; - - endif; - - $i++; - - } - - return $items; - - } - - function _makeDelimitedValueList($values, $delimiter = ', ') { - - $items = ''; - $i = 0; - $count = count($values); - - if (is_array($values)): - - foreach ($values as $k) { - - $items .= $k; - - // Add commas - if ($i < $count - 1): - - $items .= $delimiter; - - endif; - - $i++; - - } - - else: - - $items = $values; - - endif; - - return $items; - - } - - function _query() { - - switch($this->_sqlParams['query_type']) { - - case 'insert': - - $ret = $this->query($this->_sql_statement); - break; - case 'select': - - $ret = $this->get_results($this->_sql_statement); - - if (array_key_exists('result_format', $this->_sqlParams)): - $ret = $this->_formatResults($ret); - endif; - - break; - - case 'update': - - $ret = $this->query($this->_sql_statement); - break; - case 'delete': - - $ret = $this->query($this->_sql_statement); - break; - } - - $this->_last_sql_statement = $this->_sql_statement; - $this->_sql_statement = ''; - $this->_sqlParams = array(); - return $ret; - - } - - function removeNs($string, $ns = '') { - - if (empty($ns)): - $ns = $this->config['ns']; - endif; - - $ns_len = strlen($ns); - return substr($string, $ns_len); - - } - - function setFormat($value) { - - $this->_sqlParams['result_format'] = $value; - return; - } - - function _formatResults($results) { - - switch ($this->_sqlParams['result_format']) { - - case "single_array": - return $results[0]; - break; - case "single_row": - return $results[0]; - break; - case "inverted_array": - return owa_lib::deconstruct_assoc($results); - break; - default: - return $results; - break; - } - - } - - /** - * Drops a table - * - */ - function dropTable($table_name) { - - return $this->query(sprintf(OWA_SQL_DROP_TABLE, $table_name)); - - } - - /** - * Change table type - * - */ - function alterTableType($table_name, $engine) { - - return $this->query(sprintf(OWA_SQL_ALTER_TABLE_TYPE, $table_name, $engine)); - - } - - - /** - * Rename a table - * - */ - function renameTable($table_name, $new_table_name) { - - return $this->query(sprintf(OWA_SQL_RENAME_TABLE, $table_name, $new_table_name)); - } - - /** - * Renames column - * idempotent - */ - function renameColumn($table_name, $old, $new, $defs) { - - return $this->query(sprintf(OWA_SQL_RENAME_COLUMN, $table_name, $old, $new, $defs)); - } - - - /** - * Adds new column to table - * idempotent - */ - function addColumn($table_name, $column_name, $column_definition) { - - return $this->query(sprintf(OWA_SQL_ADD_COLUMN, $table_name, $column_name, $column_definition)); - } - - /** - * Drops a column from a table - * - */ - function dropColumn($table_name, $column_name) { - - return $this->query(sprintf(OWA_SQL_DROP_COLUMN, $table_name, $column_name)); - - } - - /** - * Changes the definition of a column - * - */ - function modifyColumn($table_name, $column_name, $column_definition) { - - return $this->query(sprintf(OWA_SQL_MODIFY_COLUMN, $table_name, $column_name, $column_definition)); - } - - /** - * Adds index to a column - * - */ - function addIndex($table_name, $column_name, $index_definition = '') { - - return $this->query(sprintf(OWA_SQL_ADD_INDEX, $table_name, $column_name, $index_definition)); - } - - /** - * Adds index to a column - * - */ - function dropIndex($table_name, $column_name) { - - return $this->query(sprintf(OWA_SQL_DROP_INDEX, $column_name, $table_name)); - } - - /** - * Creates a new table - * - */ - function createTable($entity) { - - //create column defs - - $all_cols = $entity->getColumns(); - - $columns = ''; - - $table_defs = ''; - - $i = 0; - $count = count($all_cols); - - // Control loop - - foreach ($all_cols as $k => $v){ - - // get column definition - $columns .= $v.' '.$entity->getColumnDefinition($v); - - // Add commas to column statement - if ($i < $count - 1): - - $columns .= ', '; - - endif; - - $i++; - - } - - // make table options - $table_options = ''; - $options = $entity->getTableOptions(); - - // table type - switch ($options['table_type']) { - - case "disk": - $table_type = OWA_DTD_TABLE_TYPE_DISK; - break; - case "memory": - $table_type = OWA_DTD_TABLE_TYPE_MEMORY; - break; - default: - $table_type = OWA_DTD_TABLE_TYPE_DEFAULT; - - } - - $table_options .= sprintf(OWA_DTD_TABLE_TYPE, $table_type); - - // character encoding type - - // just in case the propoerties is not i nthe array, add a default value. - if (!array_key_exists('character_encoding', $options)) { - - $options['character_encoding'] = OWA_DTD_CHARACTER_ENCODING_UTF8; - } - - $table_options .= sprintf(' ' . OWA_DTD_TABLE_CHARACTER_ENCODING, $options['character_encoding']); - - return $this->query(sprintf(OWA_SQL_CREATE_TABLE, $entity->getTableName(), $columns, $table_options)); - } - - - - /** - * Begins a SQL transaction statement - * - */ - function beginTransaction() { - - return $this->query(OWA_SQL_BEGIN_TRANSACTION); - } - - /** - * Ends a SQL transaction statement - * - */ - function endTransaction() { - - return $this->query(OWA_SQL_END_TRANSACTION); - } - - function count($column_name) { - - return sprintf(OWA_SQL_COUNT, $column_name); - } - - function sum($column_name) { - - return sprintf(OWA_SQL_SUM, $column_name); - } - - function distinct($column_name) { - - return sprintf(OWA_SQL_DISTINCT, $column_name); - } - - function division($numerator, $denominator) { - - return sprintf(OWA_SQL_DIVISION, $numerator, $denominator); - } - - function round($value) { - - return sprintf(OWA_SQL_ROUND, $value); - } - - function average($value) { - - return sprintf(OWA_SQL_AVERAGE, $value); - } - - function getAffectedRows() { - - return false; - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_db extends owa_base { + + /** + * Database Connection + * + * @var object + */ + var $connection; + + var $connectionParams; + + /** + * Number of queries + * + * @var integer + */ + var $num_queries; + + /** + * Raw result object + * + * @var object + */ + var $new_result; + + /** + * Rows + * + * @var array + */ + var $result; + + /** + * Caller Params + * + * @var array + */ + var $params = array(); + + /** + * Status of selecting a databse + * + * @var boolean + */ + var $database_selection; + + /** + * Status of connection + * + * @var boolean + */ + var $connection_status; + + /** + * Number of rows in result set + * + * @var integer + */ + var $num_rows; + + /** + * Number of rows affected by insert/update/delete statements + * + * @var integer + */ + var $rows_affected; + + /** + * Microtime Start of Query + * + * @var unknown_type + */ + var $_start_time; + + /** + * Total Elapsed time of query + * + * @var unknown_type + */ + var $_total_time; + + /** + * Storage Array for components of sql queries + * + * @var array + */ + var $_sqlParams = array(); + + /** + * Sql Statement + * + * @var string + */ + var $_sql_statement; + + /** + * Last Sql Statement + * + * @var string + */ + var $_last_sql_statement; + + function __construct($db_host, $db_port, $db_name, $db_user, $db_password, $open_new_connection = true, $persistant = false) { + + $this->connectionParams = array('host' => $db_host, + 'port' => $db_port, + 'user' => $db_user, + 'password' => $db_password, + 'name' => $db_name, + 'open_new_connection' => $open_new_connection, + 'persistant' => $persistant); + + return parent::__construct(); + } + + function __destruct() { + + if ( $this->isConnectionEstablished() ) { + + $this->close(); + } + } + + function connect() { + + + return false; + } + + function pconnect() { + + return false; + } + + function close() { + + return false; + } + + function isConnectionEstablished() { + + return $this->connection_status; + } + + function getConnectionParam($name) { + + if (array_key_exists($name, $this->connectionParams)) { + return $this->connectionParams[$name]; + } + } + + /** + * Prepare string + * + * @param string $string + * @return string + */ + function prepare_string($string) { + + $chars = array("\t", "\n"); + return str_replace($chars, " ", $string); + } + + /** + * Starts the query microtimer + * + */ + function _timerStart() { + + $mtime = microtime(); + //$mtime = explode(' ', $mtime); + //$this->_start_time = $mtime[1].substr(round($mtime[0], 4), 1); + $this->_start_time = microtime(); + return; + } + + /** + * Ends the query microtimer and populates $this->_total_time + * + */ + function _timerEnd() { + + $mtime = microtime(); + //$mtime = explode(" ", $mtime); + //$endtime = $mtime[1].substr(round($mtime[0], 4), 1); + $endtime = microtime(); + //$this->_total_time = bcsub($endtime, $this->_start_time, 4); + $this->_total_time = number_format(((substr($endtime,0,9)) + (substr($endtime,-10)) - (substr($this->_start_time,0,9)) - (substr($this->_start_time,-10))),6); + + return; + + } + + function selectColumn($name, $as = '') { + + if (is_array($name)) { + $as = $name[1]; + $name = $name[0]; + } + + $this->_sqlParams['select_values'][] = array('name' => $name, 'as' => $as); + + return; + } + + function select($name, $as = '') { + return $this->selectColumn($name, $as = ''); + } + + function where($name, $value, $operator = '=') { + + if ( ! owa_lib::isEmpty( $value ) ) { + + // hack for intentional empty value + if($value == ' '){ + $value = ''; + } + + $this->_sqlParams['where'][$name] = array('name' => $name, 'value' => $value, 'operator' => $operator); + } + } + + function having($name, $value, $operator = '=') { + + if ( ! owa_lib::isEmpty( $value ) ) { + + // hack for intentional empty value + if($value == ' ') { + $value = ''; + } + + $this->_sqlParams['having'][$name] = array('name' => $name, 'value' => $value, 'operator' => $operator); + } + } + + function multiWhere($where_array = array()) { + + if (!empty($where_array)): + + foreach ($where_array as $k => $v) { + if ( ! owa_lib::isEmpty($v) ): + + if (empty($v['operator'])): + $v['operator'] = '='; + endif; + + $this->_sqlParams['where'][$k] = array('name' => $k, 'value' => $v['value'], 'operator' => $v['operator']); + endif; + } + + endif; + } + + function groupBy($col) { + + $this->_sqlParams['groupby'][] = $col; + return; + } + + function orderBy($col, $flag = '') { + + $this->_sqlParams['orderby'][] = array($col, $flag); + return; + } + + function order($flag) { + + $this->_sqlParams['order'] = $flag; + return; + } + + function limit($value) { + + $this->_sqlParams['limit'] = $value; + return; + } + + function offset($value) { + + $this->_sqlParams['offset'] = $value; + return; + } + + function set($name, $value) { + + $this->_sqlParams['set_values'][] = array('name' => $name, 'value' => $value); + return; + } + + function executeQuery() { + + switch($this->_sqlParams['query_type']) { + + case 'insert': + + return $this->_insertQuery(); + + case 'select': + + return $this->_selectQuery(); + + case 'update': + + return $this->_updateQuery(); + + case 'delete': + + return $this->_deleteQuery(); + + default: + + return $this->_query(); + } + } + + function getAllRows() { + + return $this->_selectQuery(); + } + + function getOneRow() { + + $this->limit(1); + $ret = $this->_selectQuery(); + return $ret[0]; + } + + function _setSql($sql) { + $this->_sql_statement = $sql; + } + + function selectFrom($name, $as = '') { + + if (is_array($name)) { + $as = $name[1]; + $name = $name[0]; + } + + $this->_sqlParams['query_type'] = 'select'; + $this->_sqlParams['from'][$name] = array('name' => $name, 'as' => $as); + } + + function from( $name, $as = '' ) { + + return $this->selectFrom( $name, $as ); + } + + function insertInto($table) { + + $this->_sqlParams['query_type'] = 'insert'; + $this->_sqlParams['table'] = $table; + } + + function deleteFrom($table) { + + $this->_sqlParams['query_type'] = 'delete'; + $this->_sqlParams['table'] = $table; + } + + function updateTable($table) { + + $this->_sqlParams['query_type'] = 'update'; + $this->_sqlParams['table'] = $table; + } + + function _insertQuery() { + owa_coreAPI::profile($this, __FUNCTION__, __LINE__); + $params = $this->_fetchSqlParams('set_values'); + + $count = count($params); + + $i = 0; + + $sql_cols = ''; + $sql_values = ''; + + foreach ($params as $k => $v) { + + $sql_cols .= $v['name']; + $sql_values .= "'".$this->prepare($v['value'])."'"; + + $i++; + + // Add commas + if ($i < $count): + + $sql_cols .= ", "; + $sql_values .= ", "; + + endif; + } + owa_coreAPI::profile($this, __FUNCTION__, __LINE__); + $this->_setSql(sprintf(OWA_SQL_INSERT_ROW, $this->_sqlParams['table'], $sql_cols, $sql_values)); + owa_coreAPI::profile($this, __FUNCTION__, __LINE__); + $ret = $this->_query(); + owa_coreAPI::profile($this, __FUNCTION__, __LINE__); + return $ret; + + } + + function generateSelectQuerySql() { + + $cols = ''; + $i = 0; + $params = $this->_fetchSqlParams('select_values'); + $count = count($params); + + foreach ($params as $k => $v) { + + $cols .= $v['name']; + + // Add as + if (!empty($v['as'])): + + $cols .= ' as '.$v['as']; + + endif; + + // Add commas + if ($i < $count - 1): + + $cols .= ', '; + + endif; + + $i++; + + } + + $sql = sprintf("SELECT %s FROM %s %s %s %s %s %s", + $cols, + $this->_makeFromClause(), + $this->_makeWhereClause(), + $this->_makeGroupByClause(), + $this->_makeHavingClause(), + $this->_makeOrderByClause(), + $this->_makeLimitClause() + ); + $this->_setSql($sql); + return $sql; + } + + function _selectQuery() { + + $this->generateSelectQuerySql(); + return $this->_query(); + + } + + + function _updateQuery() { + + $params = $this->_fetchSqlParams('set_values'); + + $count = count($params); + + $i = 0; + + $sql_cols = ''; + $sql_values = ''; + $set = ''; + + foreach ($params as $k => $v) { + + //$sql_cols = $sql_cols.$key; + //$sql_values = $sql_values."'".$this->prepare($value)."'"; + + // Add commas + if ($i != 0): + + $set .= ', '; + + endif; + + $set .= $v['name'] .' = \'' . $this->prepare($v['value']) . '\''; + + $i++; + } + + $this->_setSql(sprintf(OWA_SQL_UPDATE_ROW, $this->_sqlParams['table'], $set, $this->_makeWhereClause())); + + return $this->_query(); + } + + function _deleteQuery() { + + $this->_setSql(sprintf(OWA_SQL_DELETE_ROW, $this->_sqlParams['table'], $this->_makeWhereClause())); + + return $this->_query(); + } + + function rawQuery($sql) { + + $this->_setSql($sql); + + return $this->_query(); + } + + function _fetchSqlParams($sql_params_name) { + + if (array_key_exists($sql_params_name, $this->_sqlParams)): + if (!empty($this->_sqlParams[$sql_params_name])): + return $this->_sqlParams[$sql_params_name]; + else: + return false; + endif; + else: + return false; + endif; + } + + function _makeWhereClause() { + + $params = $this->_fetchSqlParams('where'); + + if ( ! empty( $params ) ) { + + return $this->_makeConstraintClause('WHERE', $params); + } + } + + function _makeHavingClause() { + + $params = $this->_fetchSqlParams('having'); + + if ( ! empty( $params ) ) { + + return $this->_makeConstraintClause('HAVING', $params); + } + } + + function _makeConstraintClause($type = 'WHERE', $params) { + + if ( ! empty( $params ) ) { + + $count = count( $params ); + $i = 0; + + $constraint = $type.' '; + + foreach ($params as $k => $v) { + + switch (strtolower($v['operator'])) { + + case '==': + $constraint .= sprintf("%s = '%s'",$v['name'], $this->prepare( $v['value'] ) ); + break; + + case 'between': + $constraint .= sprintf("%s BETWEEN '%s' AND '%s'", $v['name'], $this->prepare( $v['value']['start'] ), $this->prepare( $v['value']['end'] ) ); + break; + + case '=~': + $constraint .= sprintf("%s %s '%s'",$v['name'], OWA_SQL_REGEXP, $this->prepare( $v['value'] ) ); + break; + + case '!~': + $constraint .= sprintf("%s %s '%s'",$v['name'], OWA_SQL_NOTREGEXP, $this->prepare( $v['value'] ) ); + break; + + case '=@': + $constraint .= sprintf("LOCATE('%s', %s) > 0",$v['value'], $this->prepare( $v['name'] ) ); + break; + + case '!@': + $constraint .= sprintf("LOCATE('%s', %s) = 0",$v['value'], $this->prepare( $v['name'] ) ); + break; + + default: + $constraint .= sprintf("%s %s '%s'",$v['name'], $v['operator'], $this->prepare( $v['value'] ) ); + break; + } + + if ($i < $count - 1) { + + $constraint .= " AND "; + } + + $i++; + } + + return $constraint; + } + } + + function join($type, $table, $as, $foreign_key, $primary_key = '') { + + if (!$primary_key) { + + if (!$as) { + $as = $table; + } + + $primary_key = $as.'.id'; + } + + + + $this->_sqlParams['joins'][$as] = array('type' => $type, + 'table' => $table, + 'as' => $as, + 'foreign_key' => $foreign_key, + 'primary_key' => $primary_key); + + } + + function prepare ( $string ) { + + return $string; + } + + function _makeJoinClause() { + + $params = $this->_fetchSqlParams('joins'); + + if (!empty($params)): + + $join_clause = ''; + + foreach ($params as $k => $v) { + + if (!empty($v['as'])): + $join_clause .= sprintf(" %s %s AS %s ON %s = %s", $v['type'], + $v['table'], + $v['as'], + $v['foreign_key'], + $v['primary_key']); + else: + $join_clause .= sprintf(" %s %s ON %s = %s", $v['type'], + $v['table'], $v['foreign_key'], + $v['primary_key']); + endif; + + + + } + + return $join_clause; + + else: + return; + endif; + + } + + function _makeFromClause() { + + $from = ''; + $i = 0; + $params = $this->_fetchSqlParams('from'); + + if(!empty($params)): + + $count = count($params); + + foreach ($params as $k => $v) { + + $from .= $v['name']; + + // Add as + if (!empty($v['as'])): + + $from .= ' as '.$v['as']; + + endif; + + // Add commas + if ($i < $count - 1): + + $from .= ', '; + + endif; + + $i++; + + } + + $from .= $this->_makeJoinClause(); + + return $from; + else: + $this->e->debug("No SQL FROM params set."); + return false; + endif; + + } + + function _makeGroupByClause() { + + $params = $this->_fetchSqlParams('groupby'); + + if (!empty($params)): + + return sprintf("GROUP BY %s", $this->_makeDelimitedValueList($params)); + + else: + return; + endif; + + + } + + function _makeOrderByClause() { + + $sorts = $this->_fetchSqlParams('orderby'); + //print_r($sorts); + if (!empty($sorts)): + + $order = $this->_fetchSqlParams('order'); + + $i = 1; + $sort_string = ''; + $count = count($sorts); + foreach ($sorts as $sort) { + + // needed for backwards compatability. + if (!isset($sort[1])) { + $sort[1] = $order; + } + + $sort_string .= sprintf("%s %s",$sort[0], $sort[1]); + if ($i < $count) { + $sort_string .= ', '; + } + + $i++; + } + + return sprintf("ORDER BY %s", $sort_string); + + else: + return; + endif; + + + } + + function _makeLimitClause() { + + $param = $this->_fetchSqlParams('limit'); + + if(!empty($param)): + $limit = sprintf("LIMIT %d", $param); + + $offset = $this->_makeOffsetClause(); + + $ret = $limit . ' ' . $offset; + + return $ret; + else: + return; + endif; + + } + + function _makeOffsetClause() { + + $param = $this->_fetchSqlParams('offset'); + + if(!empty($param)): + return sprintf("OFFSET %d", $param); + else: + return; + endif; + + } + + + /** + * Creates a delimited value list from an array or arrays. + * + */ + function _makeDelimitedValueListArray($values, $delimiter = ', ', $inner_delimiter = ' ') { + + $items = ''; + $i = 0; + $count = count($values); + + //print_r($values); + + foreach ($values as $k) { + + $items .= implode($inner_delimiter, $k); + + // Add commas + if ($i < $count - 1): + + $items .= $delimiter; + + endif; + + $i++; + + } + + return $items; + + } + + function _makeDelimitedValueList($values, $delimiter = ', ') { + + $items = ''; + $i = 0; + $count = count($values); + + if (is_array($values)): + + foreach ($values as $k) { + + $items .= $k; + + // Add commas + if ($i < $count - 1): + + $items .= $delimiter; + + endif; + + $i++; + + } + + else: + + $items = $values; + + endif; + + return $items; + + } + + function _query() { + + switch($this->_sqlParams['query_type']) { + + case 'insert': + + $ret = $this->query($this->_sql_statement); + break; + case 'select': + + $ret = $this->get_results($this->_sql_statement); + + if (array_key_exists('result_format', $this->_sqlParams)): + $ret = $this->_formatResults($ret); + endif; + + break; + + case 'update': + + $ret = $this->query($this->_sql_statement); + break; + case 'delete': + + $ret = $this->query($this->_sql_statement); + break; + } + + $this->_last_sql_statement = $this->_sql_statement; + $this->_sql_statement = ''; + $this->_sqlParams = array(); + return $ret; + + } + + function removeNs($string, $ns = '') { + + if (empty($ns)): + $ns = $this->config['ns']; + endif; + + $ns_len = strlen($ns); + return substr($string, $ns_len); + + } + + function setFormat($value) { + + $this->_sqlParams['result_format'] = $value; + return; + } + + function _formatResults($results) { + + switch ($this->_sqlParams['result_format']) { + + case "single_array": + return $results[0]; + break; + case "single_row": + return $results[0]; + break; + case "inverted_array": + return owa_lib::deconstruct_assoc($results); + break; + default: + return $results; + break; + } + + } + + /** + * Drops a table + * + */ + function dropTable($table_name) { + + return $this->query(sprintf(OWA_SQL_DROP_TABLE, $table_name)); + + } + + /** + * Change table type + * + */ + function alterTableType($table_name, $engine) { + + return $this->query(sprintf(OWA_SQL_ALTER_TABLE_TYPE, $table_name, $engine)); + + } + + + /** + * Rename a table + * + */ + function renameTable($table_name, $new_table_name) { + + return $this->query(sprintf(OWA_SQL_RENAME_TABLE, $table_name, $new_table_name)); + } + + /** + * Renames column + * idempotent + */ + function renameColumn($table_name, $old, $new, $defs) { + + return $this->query(sprintf(OWA_SQL_RENAME_COLUMN, $table_name, $old, $new, $defs)); + } + + + /** + * Adds new column to table + * idempotent + */ + function addColumn($table_name, $column_name, $column_definition) { + + return $this->query(sprintf(OWA_SQL_ADD_COLUMN, $table_name, $column_name, $column_definition)); + } + + /** + * Drops a column from a table + * + */ + function dropColumn($table_name, $column_name) { + + return $this->query(sprintf(OWA_SQL_DROP_COLUMN, $table_name, $column_name)); + + } + + /** + * Changes the definition of a column + * + */ + function modifyColumn($table_name, $column_name, $column_definition) { + + return $this->query(sprintf(OWA_SQL_MODIFY_COLUMN, $table_name, $column_name, $column_definition)); + } + + /** + * Adds index to a column + * + */ + function addIndex($table_name, $column_name, $index_definition = '') { + + return $this->query(sprintf(OWA_SQL_ADD_INDEX, $table_name, $column_name, $index_definition)); + } + + /** + * Adds index to a column + * + */ + function dropIndex($table_name, $column_name) { + + return $this->query(sprintf(OWA_SQL_DROP_INDEX, $column_name, $table_name)); + } + + /** + * Creates a new table + * + */ + function createTable($entity) { + + //create column defs + + $all_cols = $entity->getColumns(); + + $columns = ''; + + $table_defs = ''; + + $i = 0; + $count = count($all_cols); + + // Control loop + + foreach ($all_cols as $k => $v){ + + // get column definition + $columns .= $v.' '.$entity->getColumnDefinition($v); + + // Add commas to column statement + if ($i < $count - 1): + + $columns .= ', '; + + endif; + + $i++; + + } + + // make table options + $table_options = ''; + $options = $entity->getTableOptions(); + + // table type + switch ($options['table_type']) { + + case "disk": + $table_type = OWA_DTD_TABLE_TYPE_DISK; + break; + case "memory": + $table_type = OWA_DTD_TABLE_TYPE_MEMORY; + break; + default: + $table_type = OWA_DTD_TABLE_TYPE_DEFAULT; + + } + + $table_options .= sprintf(OWA_DTD_TABLE_TYPE, $table_type); + + // character encoding type + + // just in case the propoerties is not i nthe array, add a default value. + if (!array_key_exists('character_encoding', $options)) { + + $options['character_encoding'] = OWA_DTD_CHARACTER_ENCODING_UTF8; + } + + $table_options .= sprintf(' ' . OWA_DTD_TABLE_CHARACTER_ENCODING, $options['character_encoding']); + + return $this->query(sprintf(OWA_SQL_CREATE_TABLE, $entity->getTableName(), $columns, $table_options)); + } + + + + /** + * Begins a SQL transaction statement + * + */ + function beginTransaction() { + + return $this->query(OWA_SQL_BEGIN_TRANSACTION); + } + + /** + * Ends a SQL transaction statement + * + */ + function endTransaction() { + + return $this->query(OWA_SQL_END_TRANSACTION); + } + + function count($column_name) { + + return sprintf(OWA_SQL_COUNT, $column_name); + } + + function sum($column_name) { + + return sprintf(OWA_SQL_SUM, $column_name); + } + + function distinct($column_name) { + + return sprintf(OWA_SQL_DISTINCT, $column_name); + } + + function division($numerator, $denominator) { + + return sprintf(OWA_SQL_DIVISION, $numerator, $denominator); + } + + function round($value) { + + return sprintf(OWA_SQL_ROUND, $value); + } + + function average($value) { + + return sprintf(OWA_SQL_AVERAGE, $value); + } + + function getAffectedRows() { + + return false; + } +} + ?> \ No newline at end of file diff --git a/owa_entity.php b/owa_entity.php index 4c3c7e1ba..2719bb7c2 100644 --- a/owa_entity.php +++ b/owa_entity.php @@ -1,736 +1,736 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_entity { - - var $name; - var $properties = array(); - var $_tableProperties = array(); - var $wasPersisted; - var $cache; - - function init() { - - // get the full property list - $properties = $this->getEntityPropertyList(); - - foreach ( $properties as $col_name => $col_props ) { - - // create the column obj with the proper name and data type - $col = new owa_dbColumn( $col_name, $col_props['dtd'] ); - - // Evaluate the type of column that needs to be created - if ( array_key_exists( 'type', $col_props) ) { - - switch ( $col_props['type'] ) { - - case 'primary_key': - - $col->setPrimaryKey(); - - break; - - case 'foreign_key': - - if ( array_key_exists( 'linked_entity', $col_props ) && ! empty( $col_props['linked_entity'] ) ) { - - $col->setForeignKey( $col_props['linked_entity'] ); - } - - break; - } - } - - // should an index be created for the column? - if ( array_key_exists('index', $col_props ) ) { - - switch ( $col_props['index'] ) { - - case true: - - $col->setindex(); - - break; - } - } - - // add the full configured col to entity property list - $this->setProperty( $col ); - } - } - - - function _getProperties() { - - $properties = array(); - - if (!empty($this->properties)) { - $vars = $this->properties; - } - - foreach ($vars as $k => $v) { - - $properties[$k] = $v->getValue(); - - } - - return $properties; - } - - /** - * Return Array or string of column names used for SQL queries - e.g. like " tablename.fieldname as namespace.fieldname" - * - * @param boolean $return_as_string If false array is returned - * @param string $as_namespace Optional namespace for fields - * @param boolean $table_namespace - */ - public function getColumns($return_as_string = false, $as_namespace = '', $table_namespace = false) { - - if (!empty($this->properties)) { - $all_cols = array_keys($this->properties); - $all_cols = array_flip($all_cols); - } - - //print_r($all_cols); - - $table = $this->getTableName(); - $new_cols = array(); - $ns = ''; - $as = ''; - - if (!empty($table_namespace)): - $ns = $table.'.'; - endif; - - foreach ($all_cols as $k => $v) { - - if (!empty($as_namespace)): - $as = ' AS '.$as_namespace.$k; - endif; - - $new_cols[] = $ns.$k.$as; - } - - // add implode as string here - - if ($return_as_string == true): - $new_cols = implode(', ', $new_cols); - endif; - - //print_r($new_cols); - return $new_cols; - - } - - /** - * Sets object attributes - * - * @param unknown_type $array - */ - function setProperties($array, $apply_filters = false) { - - $properties = $this->getColumns(); - - foreach ($properties as $k => $v) { - - //if ( ! empty( $array[$v] ) ) { - if ( array_key_exists( $v, $array ) ) { - if ( ! empty( $this->properties ) ) { - $this->set($v, $array[$v], $apply_filters); - } - } - } - } - - function setGuid($string) { - - return owa_lib::setStringGuid($string); - - } - - function set($name, $value, $filter = true) { - - if ( array_key_exists( $name, $this->properties ) ) { - $method = $name.'SetFilter'; - if ( $filter && method_exists( $this, $method ) ) { - $this->properties[$name]->setValue( $this->$method( $value ) ); - } else { - $this->properties[$name]->setValue( $value ); - } - } - } - - // depricated - function setValues($values) { - - return $this->setProperties($values); - } - - function get($name, $filter = true) { - - if (array_key_exists($name, $this->properties)) { - $method = $name.'GetFilter'; - if ( $filter && method_exists($this, $method) ) { - return $this->$method( $this->properties[$name]->getValue() ); - } else { - return $this->properties[$name]->getValue(); - } - } - } - - function getTableOptions() { - - if ($this->_tableProperties) { - if (array_key_exists('table_type', $this->_tableProperties)) { - return $this->_tableProperties['table_type']; - } - } - - return array('table_type' => 'disk'); - - } - - /** - * Persist new object - * - */ - function create() { - - $db = owa_coreAPI::dbSingleton(); - $all_cols = $this->getColumns(); - - $db->insertInto($this->getTableName()); - - // Control loop - foreach ($all_cols as $k => $v){ - - // drop column is it is marked as auto-incement as DB will take care of that. - if ($this->properties[$v]->auto_increment === true) { - ; - } else { - - $db->set($v, $this->get($v, false)); - } - - } - - // Persist object - $status = $db->executeQuery(); - - // Add to Cache - if ($status == true) { - $this->addToCache(); - } - - return $status; - } - - function save() { - - if ( $this->wasPersisted ) { - return $this->update(); - } else { - return $this->create(); - } - } - - function addToCache($col = 'id') { - - if($this->isCachable()) { - $cache = owa_coreAPI::cacheSingleton(); - $cache->setCollectionExpirationPeriod($this->getTableName(), $this->getCacheExpirationPeriod()); - $cache->set($this->getTableName(), $col.$this->get('id'), $this, $this->getCacheExpirationPeriod()); - } - } - - /** - * Update all properties of an Existing object - * - */ - function update($where = '') { - - $db = owa_coreAPI::dbSingleton(); - $db->updateTable($this->getTableName()); - - // get column list - $all_cols = $this->getColumns(); - - - // Control loop - foreach ($all_cols as $k => $v){ - - // drop column is it is marked as auto-incement as DB will take care of that. - - if ($this->get($v, false)) { - $db->set($v, $this->get($v, false)); - } - } - - if(empty($where)): - $id = $this->get('id'); - $db->where('id', $id); - - else: - $db->where($where, $this->get($where)); - endif; - - // Persist object - $status = $db->executeQuery(); - // Add to Cache - if ($status === true) { - $this->addToCache(); - } - - return $status; - - } - - /** - * Update named list of properties of an existing object - * - * @param array $named_properties - * @param array $where - * @return boolean - */ - function partialUpdate($named_properties, $where) { - - $db = owa_coreAPI::dbSingleton(); - $db->updateTable($this->getTableName()); - - foreach ($named_properties as $v) { - - if ($this->get($v)){ - $db->set($v, $this->get($v)); - } - } - - if(empty($where)): - $db->where('id', $this->get('id')); - else: - $db->where($where, $this->get($where)); - endif; - - // Persist object - $status = $db->executeQuery(); - // Add to Cache - if ($status == true) { - $this->addToCache(); - } - - return $status; - } - - - /** - * Delete Object - * - */ - function delete($value = '', $col = 'id') { - - $db = owa_coreAPI::dbSingleton(); - $db->deleteFrom($this->getTableName()); - - if (empty($value)) { - $value = $this->get('id'); - } - - $db->where($col, $value); - - $status = $db->executeQuery(); - - // Delete from Cache - if ( $status ){ - if ($this->isCachable()) { - owa_coreAPI::debug('about to remove from cache'); - $cache = owa_coreAPI::cacheSingleton(); - $cache->remove($this->getTableName(), $col.$value); - } - } - - return $status; - - } - - function load($value, $col = 'id') { - - return $this->getByColumn($col, $value); - - } - - function getByPk($col, $value) { - - return $this->getByColumn($col, $value); - - } - - function getByColumn($col, $value) { - - if ( ! $col ) { - throw new Exception("No column name passed."); - } - - if ( ! $value ) { - throw new Exception("No value passed."); - } - - $cache_obj = ''; - - if ($this->isCachable()) { - $cache = owa_coreAPI::cacheSingleton(); - $cache->setCollectionExpirationPeriod($this->getTableName(), $this->getCacheExpirationPeriod()); - $cache_obj = $cache->get($this->getTableName(), $col.$value); - } - - if (!empty($cache_obj)) { - - $cache_obj_properties = $cache_obj->_getProperties(); - $this->setProperties($cache_obj_properties); - $this->wasPersisted = true; - - } else { - - $db = owa_coreAPI::dbSingleton(); - $db->selectFrom($this->getTableName()); - $db->selectColumn('*'); - owa_coreAPI::debug("Col: $col, value: $value"); - $db->where($col, $value); - $properties = $db->getOneRow(); - - if (!empty($properties)) { - - $this->setProperties($properties); - $this->wasPersisted = true; - // add to cache - $this->addToCache($col); - owa_coreAPI::debug('entity loaded from db'); - } - } - } - - function getTableName() { - - if ($this->_tableProperties) { - return $this->_tableProperties['name']; - } else { - return get_class($this); - } - - } - - function getTableAlias() { - - if ($this->_tableProperties) { - return $this->_tableProperties['alias']; - } - } - - function setTableAlias( $alias ) { - - $this->_tableProperties['alias'] = $alias; - } - - function setTableName($name, $namespace = 'owa_') { - - $this->_tableProperties['alias'] = $name; - $this->_tableProperties['name'] = $namespace.$name; - } - - /** - * Sets the entity as cachable for some period of time - * - * @todo make this use the getSetting method but that requires a refactoring of - * the entity abstract class to not use an entity in it's constructor - */ - function setCachable($seconds = '') { - - $this->_tableProperties['cacheable'] = true; - - // set cache expiration period - if (!$seconds) { - // remove hard coded value. fix this see note above. - //$seconds = owa_coreAPI::getSetting('base', 'default_cache_expiration_period'); - $seconds = 604800; - } - - $this->setCacheExpirationPeriod($seconds); - } - - function isCachable() { - - if (owa_coreAPI::getSetting('base', 'cache_objects')) { - if (array_key_exists('cacheable', $this->_tableProperties)) { - return $this->_tableProperties['cacheable']; - } - } else { - return false; - } - - } - - function setPrimaryKey($col) { - //backwards compatability - $this->properties[$col]->setPrimaryKey(); - $this->_tableProperties['primary_key'] = $col; - - } - - function getForeignKeyColumn($entity) { - if (array_key_exists('relatedEntities', $this->_tableProperties)) { - if (array_key_exists($entity, $this->_tableProperties['relatedEntities'])) { - return $this->_tableProperties['relatedEntities'][$entity]; - } - } - } - - function isForeignKeyColumn($col) { - - if (array_key_exists($col, $this->properties)) { - return $this->properties[$col]->isForeignKey(); - } - } - - function getAllForeignKeys() { - - return; - } - - /** - * Create Table - * - * Handled by DB abstraction layer because the SQL associated with this is way too DB specific - */ - function createTable() { - - $db = owa_coreAPI::dbSingleton(); - // Persist table - $status = $db->createTable($this); - - if ($status == true): - owa_coreAPI::notice(sprintf("%s Table Created.", $this->getTableName())); - return true; - else: - owa_coreAPI::notice(sprintf("%s Table Creation Failed.", $this->getTableName())); - return false; - endif; - - } - - /** - * DROP Table - * - * Drops a table. will throw error is table does not exist - */ - function dropTable() { - - $db = owa_coreAPI::dbSingleton(); - // Persist table - $status = $db->dropTable($this->getTableName()); - - if ($status == true): - return true; - else: - return false; - endif; - - } - - function addColumn($column_name) { - - $def = $this->getColumnDefinition($column_name); - // Persist table - $db = owa_coreAPI::dbSingleton(); - $status = $db->addColumn($this->getTableName(), $column_name, $def); - - if ($status == true): - return true; - else: - return false; - endif; - - } - - function dropColumn($column_name) { - - $db = owa_coreAPI::dbSingleton(); - $status = $db->dropColumn($this->getTableName(), $column_name); - - if ($status == true): - return true; - else: - return false; - endif; - - } - - function modifyColumn($column_name) { - - $def = $this->getColumnDefinition($column_name); - $db = owa_coreAPI::dbSingleton(); - $status = $db->modifyColumn($this->getTableName(), $column_name, $def); - - if ($status == true): - return true; - else: - return false; - endif; - - - } - - function renameColumn($old_column_name, $column_name, $use_old_column_for_defs = false) { - - if ($use_old_column_for_defs) { - $def = $this->getColumnDefinition($old_column_name); - } else { - $def = $this->getColumnDefinition($column_name); - } - - $db = owa_coreAPI::dbSingleton(); - $status = $db->renameColumn($this->getTableName(), $old_column_name, $column_name, $def); - - if ($status == true): - return true; - else: - return false; - endif; - - } - - function renameTable($new_table_name) { - - $db = owa_coreAPI::dbSingleton(); - $status = $db->renameTable($this->getTableName(), $new_table_name); - - if ($status == true): - return true; - else: - return false; - endif; - return; - } - - function getColumnDefinition($column_name) { - - if (empty($this->properties)) { - return $this->$column_name->getDefinition(); - } else { - return $this->properties[$column_name]->getDefinition(); - } - } - - function setProperty($obj) { - - $this->properties[$obj->get('name')] = $obj; - - if ($obj->isForeignKey()) { - $fk = $obj->getForeignKey(); - - $this->_tableProperties['relatedEntities'][$fk[0]] = $obj->getName(); - $this->_tableProperties['foreign_keys'][$obj->getName()] = $fk[0]; - } - - } - - function getProperty($name) { - if (array_key_exists($name, $this->properties)) { - return $this->properties[$name]; - } - } - - function generateRandomUid($seed = '') { - - return owa_lib::generateRandomUid(); - - //return crc32($_SERVER['SERVER_ADDR'].$_SERVER['SERVER_NAME'].getmypid().$this->getTableName().microtime().$seed.rand()); - } - - /** - * Create guid from string - * - * @param string $string - * @return integer - */ - function generateId($string) { - //require_once(OWA_DIR.'owa_lib.php'); - return owa_lib::setStringGuid($string); - } - - function setCacheExpirationPeriod($seconds) { - - $this->_tableProperties['cache_expiration_period'] = $seconds; - } - - function getCacheExpirationPeriod() { - - if (array_key_exists('cache_expiration_period', $this->_tableProperties)) { - return $this->_tableProperties['cache_expiration_period']; - } else { - // default of thirty days - return (3600); - } - } - - function getName() { - - return $this->name; - } - - function setSummaryLevel($num) { - - $this->_tableProperties['summary_level'] = $num; - } - - function getSummaryLevel() { - - if (array_key_exists('summary_level', $this->_tableProperties)) { - - return $this->_tableProperties['summary_level']; - - } else { - - return 0; - } - } - - function setCharacterEncoding($encoding) { - - $this->_tableProperties['character_encoding'] = $encoding; - } - - function wasPersisted() { - return $this->wasPersisted; - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_entity { + + var $name; + var $properties = array(); + var $_tableProperties = array(); + var $wasPersisted; + var $cache; + + function init() { + + // get the full property list + $properties = $this->getEntityPropertyList(); + + foreach ( $properties as $col_name => $col_props ) { + + // create the column obj with the proper name and data type + $col = new owa_dbColumn( $col_name, $col_props['dtd'] ); + + // Evaluate the type of column that needs to be created + if ( array_key_exists( 'type', $col_props) ) { + + switch ( $col_props['type'] ) { + + case 'primary_key': + + $col->setPrimaryKey(); + + break; + + case 'foreign_key': + + if ( array_key_exists( 'linked_entity', $col_props ) && ! empty( $col_props['linked_entity'] ) ) { + + $col->setForeignKey( $col_props['linked_entity'] ); + } + + break; + } + } + + // should an index be created for the column? + if ( array_key_exists('index', $col_props ) ) { + + switch ( $col_props['index'] ) { + + case true: + + $col->setindex(); + + break; + } + } + + // add the full configured col to entity property list + $this->setProperty( $col ); + } + } + + + function _getProperties() { + + $properties = array(); + + if (!empty($this->properties)) { + $vars = $this->properties; + } + + foreach ($vars as $k => $v) { + + $properties[$k] = $v->getValue(); + + } + + return $properties; + } + + /** + * Return Array or string of column names used for SQL queries - e.g. like " tablename.fieldname as namespace.fieldname" + * + * @param boolean $return_as_string If false array is returned + * @param string $as_namespace Optional namespace for fields + * @param boolean $table_namespace + */ + public function getColumns($return_as_string = false, $as_namespace = '', $table_namespace = false) { + + if (!empty($this->properties)) { + $all_cols = array_keys($this->properties); + $all_cols = array_flip($all_cols); + } + + //print_r($all_cols); + + $table = $this->getTableName(); + $new_cols = array(); + $ns = ''; + $as = ''; + + if (!empty($table_namespace)): + $ns = $table.'.'; + endif; + + foreach ($all_cols as $k => $v) { + + if (!empty($as_namespace)): + $as = ' AS '.$as_namespace.$k; + endif; + + $new_cols[] = $ns.$k.$as; + } + + // add implode as string here + + if ($return_as_string == true): + $new_cols = implode(', ', $new_cols); + endif; + + //print_r($new_cols); + return $new_cols; + + } + + /** + * Sets object attributes + * + * @param unknown_type $array + */ + function setProperties($array, $apply_filters = false) { + + $properties = $this->getColumns(); + + foreach ($properties as $k => $v) { + + //if ( ! empty( $array[$v] ) ) { + if ( array_key_exists( $v, $array ) ) { + if ( ! empty( $this->properties ) ) { + $this->set($v, $array[$v], $apply_filters); + } + } + } + } + + function setGuid($string) { + + return owa_lib::setStringGuid($string); + + } + + function set($name, $value, $filter = true) { + + if ( array_key_exists( $name, $this->properties ) ) { + $method = $name.'SetFilter'; + if ( $filter && method_exists( $this, $method ) ) { + $this->properties[$name]->setValue( $this->$method( $value ) ); + } else { + $this->properties[$name]->setValue( $value ); + } + } + } + + // depricated + function setValues($values) { + + return $this->setProperties($values); + } + + function get($name, $filter = true) { + + if (array_key_exists($name, $this->properties)) { + $method = $name.'GetFilter'; + if ( $filter && method_exists($this, $method) ) { + return $this->$method( $this->properties[$name]->getValue() ); + } else { + return $this->properties[$name]->getValue(); + } + } + } + + function getTableOptions() { + + if ($this->_tableProperties) { + if (array_key_exists('table_type', $this->_tableProperties)) { + return $this->_tableProperties['table_type']; + } + } + + return array('table_type' => 'disk'); + + } + + /** + * Persist new object + * + */ + function create() { + + $db = owa_coreAPI::dbSingleton(); + $all_cols = $this->getColumns(); + + $db->insertInto($this->getTableName()); + + // Control loop + foreach ($all_cols as $k => $v){ + + // drop column is it is marked as auto-incement as DB will take care of that. + if ($this->properties[$v]->auto_increment === true) { + ; + } else { + + $db->set($v, $this->get($v, false)); + } + + } + + // Persist object + $status = $db->executeQuery(); + + // Add to Cache + if ($status == true) { + $this->addToCache(); + } + + return $status; + } + + function save() { + + if ( $this->wasPersisted ) { + return $this->update(); + } else { + return $this->create(); + } + } + + function addToCache($col = 'id') { + + if($this->isCachable()) { + $cache = owa_coreAPI::cacheSingleton(); + $cache->setCollectionExpirationPeriod($this->getTableName(), $this->getCacheExpirationPeriod()); + $cache->set($this->getTableName(), $col.$this->get('id'), $this, $this->getCacheExpirationPeriod()); + } + } + + /** + * Update all properties of an Existing object + * + */ + function update($where = '') { + + $db = owa_coreAPI::dbSingleton(); + $db->updateTable($this->getTableName()); + + // get column list + $all_cols = $this->getColumns(); + + + // Control loop + foreach ($all_cols as $k => $v){ + + // drop column is it is marked as auto-incement as DB will take care of that. + + if ($this->get($v, false)) { + $db->set($v, $this->get($v, false)); + } + } + + if(empty($where)): + $id = $this->get('id'); + $db->where('id', $id); + + else: + $db->where($where, $this->get($where)); + endif; + + // Persist object + $status = $db->executeQuery(); + // Add to Cache + if ($status === true) { + $this->addToCache(); + } + + return $status; + + } + + /** + * Update named list of properties of an existing object + * + * @param array $named_properties + * @param array $where + * @return boolean + */ + function partialUpdate($named_properties, $where) { + + $db = owa_coreAPI::dbSingleton(); + $db->updateTable($this->getTableName()); + + foreach ($named_properties as $v) { + + if ($this->get($v)){ + $db->set($v, $this->get($v)); + } + } + + if(empty($where)): + $db->where('id', $this->get('id')); + else: + $db->where($where, $this->get($where)); + endif; + + // Persist object + $status = $db->executeQuery(); + // Add to Cache + if ($status == true) { + $this->addToCache(); + } + + return $status; + } + + + /** + * Delete Object + * + */ + function delete($value = '', $col = 'id') { + + $db = owa_coreAPI::dbSingleton(); + $db->deleteFrom($this->getTableName()); + + if (empty($value)) { + $value = $this->get('id'); + } + + $db->where($col, $value); + + $status = $db->executeQuery(); + + // Delete from Cache + if ( $status ){ + if ($this->isCachable()) { + owa_coreAPI::debug('about to remove from cache'); + $cache = owa_coreAPI::cacheSingleton(); + $cache->remove($this->getTableName(), $col.$value); + } + } + + return $status; + + } + + function load($value, $col = 'id') { + + return $this->getByColumn($col, $value); + + } + + function getByPk($col, $value) { + + return $this->getByColumn($col, $value); + + } + + function getByColumn($col, $value) { + + if ( ! $col ) { + throw new Exception("No column name passed."); + } + + if ( ! $value ) { + throw new Exception("No value passed."); + } + + $cache_obj = ''; + + if ($this->isCachable()) { + $cache = owa_coreAPI::cacheSingleton(); + $cache->setCollectionExpirationPeriod($this->getTableName(), $this->getCacheExpirationPeriod()); + $cache_obj = $cache->get($this->getTableName(), $col.$value); + } + + if (!empty($cache_obj)) { + + $cache_obj_properties = $cache_obj->_getProperties(); + $this->setProperties($cache_obj_properties); + $this->wasPersisted = true; + + } else { + + $db = owa_coreAPI::dbSingleton(); + $db->selectFrom($this->getTableName()); + $db->selectColumn('*'); + owa_coreAPI::debug("Col: $col, value: $value"); + $db->where($col, $value); + $properties = $db->getOneRow(); + + if (!empty($properties)) { + + $this->setProperties($properties); + $this->wasPersisted = true; + // add to cache + $this->addToCache($col); + owa_coreAPI::debug('entity loaded from db'); + } + } + } + + function getTableName() { + + if ($this->_tableProperties) { + return $this->_tableProperties['name']; + } else { + return get_class($this); + } + + } + + function getTableAlias() { + + if ($this->_tableProperties) { + return $this->_tableProperties['alias']; + } + } + + function setTableAlias( $alias ) { + + $this->_tableProperties['alias'] = $alias; + } + + function setTableName($name, $namespace = 'owa_') { + + $this->_tableProperties['alias'] = $name; + $this->_tableProperties['name'] = $namespace.$name; + } + + /** + * Sets the entity as cachable for some period of time + * + * @todo make this use the getSetting method but that requires a refactoring of + * the entity abstract class to not use an entity in it's constructor + */ + function setCachable($seconds = '') { + + $this->_tableProperties['cacheable'] = true; + + // set cache expiration period + if (!$seconds) { + // remove hard coded value. fix this see note above. + //$seconds = owa_coreAPI::getSetting('base', 'default_cache_expiration_period'); + $seconds = 604800; + } + + $this->setCacheExpirationPeriod($seconds); + } + + function isCachable() { + + if (owa_coreAPI::getSetting('base', 'cache_objects')) { + if (array_key_exists('cacheable', $this->_tableProperties)) { + return $this->_tableProperties['cacheable']; + } + } else { + return false; + } + + } + + function setPrimaryKey($col) { + //backwards compatability + $this->properties[$col]->setPrimaryKey(); + $this->_tableProperties['primary_key'] = $col; + + } + + function getForeignKeyColumn($entity) { + if (array_key_exists('relatedEntities', $this->_tableProperties)) { + if (array_key_exists($entity, $this->_tableProperties['relatedEntities'])) { + return $this->_tableProperties['relatedEntities'][$entity]; + } + } + } + + function isForeignKeyColumn($col) { + + if (array_key_exists($col, $this->properties)) { + return $this->properties[$col]->isForeignKey(); + } + } + + function getAllForeignKeys() { + + return; + } + + /** + * Create Table + * + * Handled by DB abstraction layer because the SQL associated with this is way too DB specific + */ + function createTable() { + + $db = owa_coreAPI::dbSingleton(); + // Persist table + $status = $db->createTable($this); + + if ($status == true): + owa_coreAPI::notice(sprintf("%s Table Created.", $this->getTableName())); + return true; + else: + owa_coreAPI::notice(sprintf("%s Table Creation Failed.", $this->getTableName())); + return false; + endif; + + } + + /** + * DROP Table + * + * Drops a table. will throw error is table does not exist + */ + function dropTable() { + + $db = owa_coreAPI::dbSingleton(); + // Persist table + $status = $db->dropTable($this->getTableName()); + + if ($status == true): + return true; + else: + return false; + endif; + + } + + function addColumn($column_name) { + + $def = $this->getColumnDefinition($column_name); + // Persist table + $db = owa_coreAPI::dbSingleton(); + $status = $db->addColumn($this->getTableName(), $column_name, $def); + + if ($status == true): + return true; + else: + return false; + endif; + + } + + function dropColumn($column_name) { + + $db = owa_coreAPI::dbSingleton(); + $status = $db->dropColumn($this->getTableName(), $column_name); + + if ($status == true): + return true; + else: + return false; + endif; + + } + + function modifyColumn($column_name) { + + $def = $this->getColumnDefinition($column_name); + $db = owa_coreAPI::dbSingleton(); + $status = $db->modifyColumn($this->getTableName(), $column_name, $def); + + if ($status == true): + return true; + else: + return false; + endif; + + + } + + function renameColumn($old_column_name, $column_name, $use_old_column_for_defs = false) { + + if ($use_old_column_for_defs) { + $def = $this->getColumnDefinition($old_column_name); + } else { + $def = $this->getColumnDefinition($column_name); + } + + $db = owa_coreAPI::dbSingleton(); + $status = $db->renameColumn($this->getTableName(), $old_column_name, $column_name, $def); + + if ($status == true): + return true; + else: + return false; + endif; + + } + + function renameTable($new_table_name) { + + $db = owa_coreAPI::dbSingleton(); + $status = $db->renameTable($this->getTableName(), $new_table_name); + + if ($status == true): + return true; + else: + return false; + endif; + return; + } + + function getColumnDefinition($column_name) { + + if (empty($this->properties)) { + return $this->$column_name->getDefinition(); + } else { + return $this->properties[$column_name]->getDefinition(); + } + } + + function setProperty($obj) { + + $this->properties[$obj->get('name')] = $obj; + + if ($obj->isForeignKey()) { + $fk = $obj->getForeignKey(); + + $this->_tableProperties['relatedEntities'][$fk[0]] = $obj->getName(); + $this->_tableProperties['foreign_keys'][$obj->getName()] = $fk[0]; + } + + } + + function getProperty($name) { + if (array_key_exists($name, $this->properties)) { + return $this->properties[$name]; + } + } + + function generateRandomUid($seed = '') { + + return owa_lib::generateRandomUid(); + + //return crc32($_SERVER['SERVER_ADDR'].$_SERVER['SERVER_NAME'].getmypid().$this->getTableName().microtime().$seed.rand()); + } + + /** + * Create guid from string + * + * @param string $string + * @return integer + */ + function generateId($string) { + //require_once(OWA_DIR.'owa_lib.php'); + return owa_lib::setStringGuid($string); + } + + function setCacheExpirationPeriod($seconds) { + + $this->_tableProperties['cache_expiration_period'] = $seconds; + } + + function getCacheExpirationPeriod() { + + if (array_key_exists('cache_expiration_period', $this->_tableProperties)) { + return $this->_tableProperties['cache_expiration_period']; + } else { + // default of thirty days + return (3600); + } + } + + function getName() { + + return $this->name; + } + + function setSummaryLevel($num) { + + $this->_tableProperties['summary_level'] = $num; + } + + function getSummaryLevel() { + + if (array_key_exists('summary_level', $this->_tableProperties)) { + + return $this->_tableProperties['summary_level']; + + } else { + + return 0; + } + } + + function setCharacterEncoding($encoding) { + + $this->_tableProperties['character_encoding'] = $encoding; + } + + function wasPersisted() { + return $this->wasPersisted; + } +} + ?> \ No newline at end of file diff --git a/owa_env.php b/owa_env.php index 5c9af53d0..8f22d439b 100644 --- a/owa_env.php +++ b/owa_env.php @@ -1,49 +1,49 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -if (!defined('OWA_PATH')) { - define('OWA_PATH', dirname(__FILE__)); -} -define('OWA_DIR', OWA_PATH . '/'); -define('OWA_MODULES_DIR', OWA_DIR.'modules/'); -define('OWA_BASE_DIR', OWA_PATH); // depricated -define('OWA_BASE_CLASSES_DIR', OWA_DIR); //depricated -define('OWA_BASE_MODULE_DIR', OWA_DIR.'modules/base/'); -define('OWA_BASE_CLASS_DIR', OWA_BASE_MODULE_DIR.'classes/'); -define('OWA_INCLUDE_DIR', OWA_DIR.'includes/'); -define('OWA_PEARLOG_DIR', OWA_INCLUDE_DIR.'Log-1.13.1'); -define('OWA_PHPMAILER_DIR', OWA_INCLUDE_DIR.'PHPMailer-6.1.4/src/'); -define('OWA_HTTPCLIENT_DIR', OWA_INCLUDE_DIR.'httpclient-2016-05-02/'); -define('OWA_PLUGIN_DIR', OWA_DIR.'plugins/'); -define('OWA_CONF_DIR', OWA_DIR.'conf/'); -define('OWA_THEMES_DIR', OWA_DIR.'themes/'); -define('OWA_VERSION', 'master'); -define('OWA_VENDOR_DIR', OWA_DIR.'vendor/'); - -?> + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +if (!defined('OWA_PATH')) { + define('OWA_PATH', dirname(__FILE__)); +} +define('OWA_DIR', OWA_PATH . '/'); +define('OWA_MODULES_DIR', OWA_DIR.'modules/'); +define('OWA_BASE_DIR', OWA_PATH); // depricated +define('OWA_BASE_CLASSES_DIR', OWA_DIR); //depricated +define('OWA_BASE_MODULE_DIR', OWA_DIR.'modules/base/'); +define('OWA_BASE_CLASS_DIR', OWA_BASE_MODULE_DIR.'classes/'); +define('OWA_INCLUDE_DIR', OWA_DIR.'includes/'); +define('OWA_PEARLOG_DIR', OWA_INCLUDE_DIR.'Log-1.13.1'); +define('OWA_PHPMAILER_DIR', OWA_INCLUDE_DIR.'PHPMailer-6.1.4/src/'); +define('OWA_HTTPCLIENT_DIR', OWA_INCLUDE_DIR.'httpclient-2016-05-02/'); +define('OWA_PLUGIN_DIR', OWA_DIR.'plugins/'); +define('OWA_CONF_DIR', OWA_DIR.'conf/'); +define('OWA_THEMES_DIR', OWA_DIR.'themes/'); +define('OWA_VERSION', 'master'); +define('OWA_VENDOR_DIR', OWA_DIR.'vendor/'); + +?> diff --git a/owa_httpRequest.php b/owa_httpRequest.php index 5645b3f13..767917c78 100644 --- a/owa_httpRequest.php +++ b/owa_httpRequest.php @@ -1,337 +1,337 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_http { - - /** - * Configuration - * - * @var array - */ - var $config; - - /** - * Error handler - * - * @var object - */ - var $e; - - /** - * The length of text contained in the snippet - * - * @var string - */ - var $snip_len = 100; - - /** - * The string that is added to the beginning and - * end of snippet text. - * - * @var string - */ - var $snip_str = '...'; - - /** - * Anchor information for a particular link - * - * @var array - */ - var $anchor_info; - - var $crawler; - - var $testcrawler; - - var $http; - - var $response; - var $response_headers; - var $response_code; - - var $request_headers; - - function __construct() { - - $c = owa_coreAPI::configSingleton(); - $this->config = $c->fetch('base'); - $this->e = owa_coreAPI::errorSingleton(); - $this->crawler = new Snoopy; - // do not allow snoopy to follow links - $this->crawler->maxredirs = 5; - $this->crawler->agent = owa_coreAPI::getSetting('base', 'owa_user_agent'); - //$this->crawler->agent = "Firefox"; - //owa_coreAPI::debug('hello from owa_http constructor'); - return; - - } - - function fetch($uri) { - //owa_coreAPI::debug('hello from owa_http fetch'); - return $this->crawler->fetch($uri); - } - - function testFetch($url) { - - $http= new http_class; - owa_coreAPI::debug('hello owa_http testfetch method'); - /* Connection timeout */ - $http->timeout=0; - /* Data transfer timeout */ - $http->data_timeout=0; - /* Output debugging information about the progress of the connection */ - $http->debug=1; - $http->user_agent = owa_coreAPI::getSetting('base', 'owa_user_agent'); - $http->follow_redirect=1; - $http->redirection_limit=5; - $http->exclude_address=""; - $http->prefer_curl=0; - $arguments = array(); - $error=$http->GetRequestArguments($url,$arguments); - $error=$http->Open($arguments); - - //for(;;) - // { - $error=$http->ReadReplyBody($body,50000); - if($error!="" || strlen($body)==0) - owa_coreAPI::debug(HtmlSpecialChars($body)); - // } - - } - - /** - * Searches a fetched html document for the anchor of a specific url - * - * @param string $link - */ - function extract_anchor($link) { - - $matches = ''; - $regex = '/]*href=\"%s\"[^>]*>(.*?)<\/a>/i'; - - //$escaped_link = str_replace(array("/", "?"), array("\/", "\?"), $link); - - $pattern = trim(sprintf($regex, preg_quote($link, '/'))); - $search = preg_match($pattern, $this->response, $matches); - //$this->e->debug('pattern: '.$pattern); - //$this->e->debug('link: '.$link); - - - if (empty($matches)) { - if (substr($link, -1) === '/') { - $link = substr($link, 0, -1); - $pattern = trim(sprintf($regex, preg_quote($link, '/'))); - $search = preg_match($pattern, $this->response, $matches); - //$this->e->debug('pattern: '.$pattern); - //$this->e->debug('link: '.$link); - } - } - - $this->e->debug('ref search: '.$search); - //$this->e->debug('ref matches: '.print_r($this->results, true)); - //$this->e->debug('ref matches: '.print_r($matches, true)); - if (isset($matches[0])) { - $this->anchor_info = array('anchor_tag' => $matches[0], 'anchor_text' => owa_lib::inputFilter($matches[0])); - $this->e->debug('Anchor info: '.print_r($this->anchor_info, true)); - } - } - - /** - * Creates a text snippet of the portion of page where the - * specific link is found. - * - * Takes fully qualified URL for the link to search for. - * - * @param string $link - * @return string - */ - function extract_anchor_snippet($link){ - - // Search the page for a specific anchor - $this->extract_anchor($link); - - if(!empty($this->anchor_info['anchor_tag'])) { - - // drop certain HTML entitities and their content - $nohtml = $this->strip_selected_tags( - $this->response, - array('title', - 'head', - 'script', - 'object', - 'style', - 'meta', - 'link', - 'rdf:'), - true); - - //$this->e->debug('Refering page content after certain html entities were dropped: '.$this->results); - - // calc len of the anchor text - $atext_len = strlen($this->anchor_info['anchor_tag']); - - // find position within document of the anchor text - $start = strpos($nohtml, $this->anchor_info['anchor_tag']); - - if ($start < $this->snip_len) { - $part1_start_pos = 0; - $part1_snip_len = $start; - } else { - $part1_start_pos = $start; - $part1_snip_len = $this->snip_len; - } - - $replace_items = array("\r\n", "\n\n", "\t", "\r", "\n"); - // Create first segment of snippet - $first_part = substr($nohtml, 0, $part1_start_pos); - $first_part = str_replace($replace_items, '', $first_part); - $first_part = strip_tags(owa_lib::inputFilter($first_part)); - //$part1 = trim(substr($nohtml, $part1_start_pos, $part1_snip_len)); - $part1 = substr($first_part,-$part1_snip_len, $part1_snip_len); - - //$part1 = str_replace(array('\r\n', '\n\n', '\t', '\r', '\n'), '', $part1); - //$part1 = owa_lib::inputFilter($part1); - // Create second segment of snippet - $part2 = trim(substr($nohtml, $start + $atext_len, $this->snip_len+300)); - $part2 = str_replace($replace_items, '', $part2); - $part2 = substr(strip_tags(owa_lib::inputFilter($part2)),0, $this->snip_len); - - // Put humpty dumpy back together again and create actual snippet - $snippet = $this->snip_str.$part1.' '.owa_lib::inputFilter($this->anchor_info['anchor_tag']).' '.$part2.$this->snip_str; - - } else { - - $snippet = ''; - - } - - return $snippet; - - } - - function extract_title() { - - preg_match('~(||(\s*(.*?)\s*))~i', $this->response, $m); - - $this->e->debug("referer title extract: ". print_r($m, true)); - - return $m[3]; - } - - function strip_selected_tags($str, $tags = array(), $stripContent = false) { - - foreach ($tags as $k => $tag){ - - if ($stripContent == true) { - $pattern = sprintf('#(<%s.*?>)(.*?)(<\/%s.*?>)#is', preg_quote($tag), preg_quote($tag)); - $str = preg_replace($pattern,"",$str); - } - $str = preg_replace($pattern, '${2}',$str); - } - - return $str; - } - - function SetupHTTP() - { - if(!IsSet($this->http)) - { - $this->http = new http_class; - $this->http->follow_redirect = 1; - $this->http->debug = 0; - $this->http->debug_response_body = 0; - $this->http->html_debug = 1; - $this->http->user_agent = owa_coreAPI::getSetting('base', 'owa_user_agent'); - $this->http->timeout = 3; - $this->http->data_timeout = 3; - } - } - - function OpenRequest($arguments, &$headers) - { - if(strlen($this->error=$this->http->Open($arguments))) - return(0); - if(strlen($this->error=$this->http->SendRequest($arguments)) - || strlen($this->error=$this->http->ReadReplyHeaders($headers))) - { - $this->http->Close(); - return(0); - } - if($this->http->response_status!=200) - { - $this->error = 'the HTTP request returned the status '.$this->http->response_status; - $this->http->Close(); - return(0); - } - return(1); - } - - function GetRequestResponse(&$response) - { - for($response = ''; ; ) - { - if(strlen($this->error=$this->http->ReadReplyBody($body, 500000))) - { - $this->http->Close(); - return(0); - } - if(strlen($body)==0) - break; - $response .= $body; - - } - $this->http->Close(); - owa_coreAPI::debug('http response code: '.$this->http->response_status); - return($response); - } - - function getRequest($url, $arguments = '', $response = '') { - - $this->SetupHTTP(); - - $this->http->GetRequestArguments($url, $arguments); - $arguments['RequestMethod']='GET'; - if(!$this->OpenRequest($arguments, $headers)) { - return(0); - } - $this->response = $this->GetRequestResponse($response); - return($this->response); - } - -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_http { + + /** + * Configuration + * + * @var array + */ + var $config; + + /** + * Error handler + * + * @var object + */ + var $e; + + /** + * The length of text contained in the snippet + * + * @var string + */ + var $snip_len = 100; + + /** + * The string that is added to the beginning and + * end of snippet text. + * + * @var string + */ + var $snip_str = '...'; + + /** + * Anchor information for a particular link + * + * @var array + */ + var $anchor_info; + + var $crawler; + + var $testcrawler; + + var $http; + + var $response; + var $response_headers; + var $response_code; + + var $request_headers; + + function __construct() { + + $c = owa_coreAPI::configSingleton(); + $this->config = $c->fetch('base'); + $this->e = owa_coreAPI::errorSingleton(); + $this->crawler = new Snoopy; + // do not allow snoopy to follow links + $this->crawler->maxredirs = 5; + $this->crawler->agent = owa_coreAPI::getSetting('base', 'owa_user_agent'); + //$this->crawler->agent = "Firefox"; + //owa_coreAPI::debug('hello from owa_http constructor'); + return; + + } + + function fetch($uri) { + //owa_coreAPI::debug('hello from owa_http fetch'); + return $this->crawler->fetch($uri); + } + + function testFetch($url) { + + $http= new http_class; + owa_coreAPI::debug('hello owa_http testfetch method'); + /* Connection timeout */ + $http->timeout=0; + /* Data transfer timeout */ + $http->data_timeout=0; + /* Output debugging information about the progress of the connection */ + $http->debug=1; + $http->user_agent = owa_coreAPI::getSetting('base', 'owa_user_agent'); + $http->follow_redirect=1; + $http->redirection_limit=5; + $http->exclude_address=""; + $http->prefer_curl=0; + $arguments = array(); + $error=$http->GetRequestArguments($url,$arguments); + $error=$http->Open($arguments); + + //for(;;) + // { + $error=$http->ReadReplyBody($body,50000); + if($error!="" || strlen($body)==0) + owa_coreAPI::debug(HtmlSpecialChars($body)); + // } + + } + + /** + * Searches a fetched html document for the anchor of a specific url + * + * @param string $link + */ + function extract_anchor($link) { + + $matches = ''; + $regex = '/]*href=\"%s\"[^>]*>(.*?)<\/a>/i'; + + //$escaped_link = str_replace(array("/", "?"), array("\/", "\?"), $link); + + $pattern = trim(sprintf($regex, preg_quote($link, '/'))); + $search = preg_match($pattern, $this->response, $matches); + //$this->e->debug('pattern: '.$pattern); + //$this->e->debug('link: '.$link); + + + if (empty($matches)) { + if (substr($link, -1) === '/') { + $link = substr($link, 0, -1); + $pattern = trim(sprintf($regex, preg_quote($link, '/'))); + $search = preg_match($pattern, $this->response, $matches); + //$this->e->debug('pattern: '.$pattern); + //$this->e->debug('link: '.$link); + } + } + + $this->e->debug('ref search: '.$search); + //$this->e->debug('ref matches: '.print_r($this->results, true)); + //$this->e->debug('ref matches: '.print_r($matches, true)); + if (isset($matches[0])) { + $this->anchor_info = array('anchor_tag' => $matches[0], 'anchor_text' => owa_lib::inputFilter($matches[0])); + $this->e->debug('Anchor info: '.print_r($this->anchor_info, true)); + } + } + + /** + * Creates a text snippet of the portion of page where the + * specific link is found. + * + * Takes fully qualified URL for the link to search for. + * + * @param string $link + * @return string + */ + function extract_anchor_snippet($link){ + + // Search the page for a specific anchor + $this->extract_anchor($link); + + if(!empty($this->anchor_info['anchor_tag'])) { + + // drop certain HTML entitities and their content + $nohtml = $this->strip_selected_tags( + $this->response, + array('title', + 'head', + 'script', + 'object', + 'style', + 'meta', + 'link', + 'rdf:'), + true); + + //$this->e->debug('Refering page content after certain html entities were dropped: '.$this->results); + + // calc len of the anchor text + $atext_len = strlen($this->anchor_info['anchor_tag']); + + // find position within document of the anchor text + $start = strpos($nohtml, $this->anchor_info['anchor_tag']); + + if ($start < $this->snip_len) { + $part1_start_pos = 0; + $part1_snip_len = $start; + } else { + $part1_start_pos = $start; + $part1_snip_len = $this->snip_len; + } + + $replace_items = array("\r\n", "\n\n", "\t", "\r", "\n"); + // Create first segment of snippet + $first_part = substr($nohtml, 0, $part1_start_pos); + $first_part = str_replace($replace_items, '', $first_part); + $first_part = strip_tags(owa_lib::inputFilter($first_part)); + //$part1 = trim(substr($nohtml, $part1_start_pos, $part1_snip_len)); + $part1 = substr($first_part,-$part1_snip_len, $part1_snip_len); + + //$part1 = str_replace(array('\r\n', '\n\n', '\t', '\r', '\n'), '', $part1); + //$part1 = owa_lib::inputFilter($part1); + // Create second segment of snippet + $part2 = trim(substr($nohtml, $start + $atext_len, $this->snip_len+300)); + $part2 = str_replace($replace_items, '', $part2); + $part2 = substr(strip_tags(owa_lib::inputFilter($part2)),0, $this->snip_len); + + // Put humpty dumpy back together again and create actual snippet + $snippet = $this->snip_str.$part1.' '.owa_lib::inputFilter($this->anchor_info['anchor_tag']).' '.$part2.$this->snip_str; + + } else { + + $snippet = ''; + + } + + return $snippet; + + } + + function extract_title() { + + preg_match('~(||(\s*(.*?)\s*))~i', $this->response, $m); + + $this->e->debug("referer title extract: ". print_r($m, true)); + + return $m[3]; + } + + function strip_selected_tags($str, $tags = array(), $stripContent = false) { + + foreach ($tags as $k => $tag){ + + if ($stripContent == true) { + $pattern = sprintf('#(<%s.*?>)(.*?)(<\/%s.*?>)#is', preg_quote($tag), preg_quote($tag)); + $str = preg_replace($pattern,"",$str); + } + $str = preg_replace($pattern, '${2}',$str); + } + + return $str; + } + + function SetupHTTP() + { + if(!IsSet($this->http)) + { + $this->http = new http_class; + $this->http->follow_redirect = 1; + $this->http->debug = 0; + $this->http->debug_response_body = 0; + $this->http->html_debug = 1; + $this->http->user_agent = owa_coreAPI::getSetting('base', 'owa_user_agent'); + $this->http->timeout = 3; + $this->http->data_timeout = 3; + } + } + + function OpenRequest($arguments, &$headers) + { + if(strlen($this->error=$this->http->Open($arguments))) + return(0); + if(strlen($this->error=$this->http->SendRequest($arguments)) + || strlen($this->error=$this->http->ReadReplyHeaders($headers))) + { + $this->http->Close(); + return(0); + } + if($this->http->response_status!=200) + { + $this->error = 'the HTTP request returned the status '.$this->http->response_status; + $this->http->Close(); + return(0); + } + return(1); + } + + function GetRequestResponse(&$response) + { + for($response = ''; ; ) + { + if(strlen($this->error=$this->http->ReadReplyBody($body, 500000))) + { + $this->http->Close(); + return(0); + } + if(strlen($body)==0) + break; + $response .= $body; + + } + $this->http->Close(); + owa_coreAPI::debug('http response code: '.$this->http->response_status); + return($response); + } + + function getRequest($url, $arguments = '', $response = '') { + + $this->SetupHTTP(); + + $this->http->GetRequestArguments($url, $arguments); + $arguments['RequestMethod']='GET'; + if(!$this->OpenRequest($arguments, $headers)) { + return(0); + } + $this->response = $this->GetRequestResponse($response); + return($this->response); + } + +} + + ?> \ No newline at end of file diff --git a/owa_install.php b/owa_install.php index 21b9d4215..de0e967d9 100644 --- a/owa_install.php +++ b/owa_install.php @@ -1,111 +1,111 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_install extends owa_base{ - - /** - * Data access object - * - * @var object - */ - var $db; - - /** - * Version of string - * - * @var string - */ - var $version; - - /** - * Params array - * - * @var array - */ - var $params; - - /** - * Module name - * - * @var unknown_type - */ - var $module; - - /** - * Constructor - * - * @return owa_install - */ - - function __construct() { - - parent::__construct(); - $this->db = owa_coreAPI::dbSingleton(); - } - - /** - * Check to see if schema is installed - * - * @return boolean - */ - function checkForSchema() { - - $table_check = array(); - //$this->e->notice(print_r($this->tables, true)); - // test for existance of tables - foreach ($this->tables as $table) { - $this->e->notice('Testing for existance of table: '. $table); - $check = $this->db->get_results(sprintf("show tables like 'owa_%s'", $table)); - //$this->e->notice(print_r($check, true)); - - // if a table is missing add it to this array - if (empty($check)): - $table_check[] = $table; - $this->e->notice('Did not find table: '. $table); - else: - $this->e->notice('Table '. $table. ' already exists.'); - endif; - } - - if (!empty($table_check)): - //$this->e->notice(sprintf("Schema Check: Tables '%s' are missing.", implode(',', $table_check))); - $this->e->notice(sprintf("Schema Check: Tables to install: %s", print_r($table_check, true))); - - return $table_check; - else: - return false; - endif; - - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_install extends owa_base{ + + /** + * Data access object + * + * @var object + */ + var $db; + + /** + * Version of string + * + * @var string + */ + var $version; + + /** + * Params array + * + * @var array + */ + var $params; + + /** + * Module name + * + * @var unknown_type + */ + var $module; + + /** + * Constructor + * + * @return owa_install + */ + + function __construct() { + + parent::__construct(); + $this->db = owa_coreAPI::dbSingleton(); + } + + /** + * Check to see if schema is installed + * + * @return boolean + */ + function checkForSchema() { + + $table_check = array(); + //$this->e->notice(print_r($this->tables, true)); + // test for existance of tables + foreach ($this->tables as $table) { + $this->e->notice('Testing for existance of table: '. $table); + $check = $this->db->get_results(sprintf("show tables like 'owa_%s'", $table)); + //$this->e->notice(print_r($check, true)); + + // if a table is missing add it to this array + if (empty($check)): + $table_check[] = $table; + $this->e->notice('Did not find table: '. $table); + else: + $this->e->notice('Table '. $table. ' already exists.'); + endif; + } + + if (!empty($table_check)): + //$this->e->notice(sprintf("Schema Check: Tables '%s' are missing.", implode(',', $table_check))); + $this->e->notice(sprintf("Schema Check: Tables to install: %s", print_r($table_check, true))); + + return $table_check; + else: + return false; + endif; + + } + +} + ?> \ No newline at end of file diff --git a/owa_lib.php b/owa_lib.php index 5a53e0ef9..4d849b183 100644 --- a/owa_lib.php +++ b/owa_lib.php @@ -1,1388 +1,1388 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_lib { - - /** - * Convert Associative Array to String - * - * @param string $inner_glue - * @param string $outer_glue - * @param array $array - * @return string - */ - public static function implode_assoc($inner_glue, $outer_glue, $array) { - $output = array(); - foreach( $array as $key => $item ) { - $output[] = $key . $inner_glue . $item; - } - - return implode($outer_glue, $output); - } - - /** - * Deconstruct Associative Array - * - * For example this takes array([1] => array(a => dog, b => cat), [2] => array(a => sheep, b => goat)) - * and tunrs it into array([a] => array(dog, sheep), [b] => array(cat, goat)) - * - * @param array $a_array - * @return array $data_arrays - * @access public - */ - public static function deconstruct_assoc($a_array) { - if (!empty($a_array)): - - $data_arrays = array(); - - if(!empty($a_array[1])) : - - foreach ($a_array as $key => $value) { - foreach ($value as $k => $v) { - $data_arrays[$k][] = $v; - - } - } - else: - //print_r($a_array[0]); - foreach ($a_array[0] as $key => $value) { - $data_arrays[$key][] = $value; - } - endif; - - return $data_arrays; - else: - return array(); - endif; - } - - - public static function decon_assoc($a_array) { - - $data_arrays = array(); - - foreach ($a_array as $key => $value) { - //foreach ($value as $k => $v) { - $data_arrays[$key][] = $value; - - //} - } - - return $data_arrays; - } - - // php 4 compatible function - public static function array_intersect_key() { - - $arrs = func_get_args(); - $result = array_shift($arrs); - foreach ($arrs as $array) { - foreach ($result as $key => $v) { - if (!array_key_exists($key, $array)) { - unset($result[$key]); - } - } - } - return $result; - } - - // php4 compatible function - public static function array_walk_recursive(&$input, $funcname, $userdata = "") - { - if (!is_callable($funcname)) - { - return false; - } - - if (!is_array($input)) - { - return false; - } - - if (is_array($funcname)) - { - $funcname = $funcname[0].'::'.$funcname[1]; - } - - - foreach ($input AS $key => $value) - { - if (is_array($input[$key])) - { - array_walk_recursive($input[$key], $funcname, $userdata); - } - else - { - $saved_value = $value; - if (!empty($userdata)) - { - $funcname($value, $key, $userdata); - } - else - { - $funcname($value, $key); - } - - if ($value != $saved_value) - { - $input[$key] = $value; - } - } - } - return true; - } - - /** - * Array of Current Time - * - * @return array - * @access public - */ - public static function time_now() { - - $timestamp = time(); - - return array( - - 'year' => date("Y", $timestamp), - 'month' => date("n", $timestamp), - 'day' => date("d", $timestamp), - 'dayofweek' => date("w", $timestamp), - 'dayofyear' => date("z", $timestamp), - 'weekofyear' => date("W", $timestamp), - 'hour' => date("G", $timestamp), - 'minute' => date("i", $timestamp), - 'second' => date("s", $timestamp), - 'timestamp' => $timestamp - ); - } - - /** - * Error Handler - * - * @param string $msg - * @access public - * @depricated - */ - function errorHandler($msg) { - require_once(OWA_PEARLOG_DIR . '/Log.php'); - $conf = array('mode' => 0755, 'timeFormat' => '%X %x'); - $error_logger = &Log::singleton('file', $this->config['error_log_file'], 'ident', $conf); - $this->error_logger->_lineFormat = '[%3$s]'; - - return; - } - - /** - * Information array for Months in the year. - * - * @return array - */ - public static function months() { - - return array( - - 1 => array('label' => 'January'), - 2 => array('label' => 'February'), - 3 => array('label' => 'March'), - 4 => array('label' => 'April'), - 5 => array('label' => 'May'), - 6 => array('label' => 'June'), - 7 => array('label' => 'July'), - 8 => array('label' => 'August'), - 9 => array('label' => 'September'), - 10 => array('label' => 'October'), - 11 => array('label' => 'November'), - 12 => array('label' => 'December') - ); - - } - - public static function days() { - - return array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31); - } - - public static function years() { - - static $years; - - if (empty($years)): - - $start_year = 2005; - - $years = array($start_year); - - $num_years = date("Y", time()) - $start_year; - - for($i=1; $i<=$num_years; $i++) { - - $years[] = $start_year + $i; - } - - $years = array_reverse($years); - - endif; - - return $years; - } - - - /** - * Returns a label from an array of months - * - * @param int $month - * @return string - */ - public static function get_month_label($month) { - - static $months; - - if (empty($months)): - - $months = owa_lib::months(); - - endif; - - return $months[$month]['label']; - - } - - - /** - * Sets the suffix for Days used in Date labels - * @depricated - * @param string $day - * @return string - */ - public static function setDaySuffix($day) { - - switch ($day) { - - case "1": - $day_suffix = 'st'; - break; - case "2": - $day_suffix = 'nd'; - break; - case "3": - $day_suffix = 'rd'; - break; - default: - $day_suffix = 'th'; - } - - return $day_suffix; - - } - - /** - * Generates the label for a date - * @depricated - * @param array $params - * @return string - */ - public static function getDatelabel($params) { - - switch ($params['period']) { - - case "day": - return sprintf("%s, %d%s %s", - owa_lib::get_month_label($params['month']), - $params['day'], - owa_lib::setDaySuffix($params['day']), - $params['year'] - ); - break; - - case "month": - return sprintf("%s %s", - owa_lib::get_month_label($params['month']), - $params['year'] - ); - break; - - case "year": - return sprintf("%s", - $params['year'] - ); - break; - case "date_range": - return sprintf("%s, %d%s %s - %s, %d%s %s", - owa_lib::get_month_label($params['month']), - $params['day'], - owa_lib::setDaySuffix($params['day']), - $params['year'], - owa_lib::get_month_label($params['month2']), - $params['day2'], - owa_lib::setDaySuffix($params['day2']), - $params['year2'] - ); - break; - } - - return false; - - } - - /** - * Array of Reporting Periods - * @depricated - * @return array - */ - public static function reporting_periods() { - - return array( - - 'today' => array('label' => 'Today'), - 'yesterday' => array('label' => 'Yesterday'), - 'this_week' => array('label' => 'This Week'), - 'this_month' => array('label' => 'This Month'), - 'this_year' => array('label' => 'This Year'), - 'last_week' => array('label' => 'Last Week'), - 'last_month' => array('label' => 'Last Month'), - 'last_year' => array('label' => 'Last Year'), - 'last_half_hour' => array('label' => 'The Last 30 Minutes'), - 'last_hour' => array('label' => 'Last Hour'), - 'last_24_hours' => array('label' => 'The Last 24 Hours'), - 'last_seven_days' => array('label' => 'The Last Seven Days'), - 'last_thirty_days' => array('label' => 'The Last Thirty Days'), - 'same_day_last_week' => array('label' => 'Same Day last Week'), - 'same_week_last_year' => array('label' => 'Same Week Last Year'), - 'same_month_last_year' => array('label' => 'Same Month Last Year'), - 'date_range' => array('label' => 'Date Range') - ); - - } - - /** - * Array of Date specific Reporting Periods - * @depricated - * @return array - */ - public static function date_reporting_periods() { - - return array( - - 'day' => array('label' => 'Day'), - 'month' => array('label' => 'Month'), - 'year' => array('label' => 'Year'), - 'date_range' => array('label' => 'Date Range') - ); - - } - - /** - * Gets label for a particular reporting period - * - * @param unknown_type $period - * @return unknown - */ - public static function get_period_label($period) { - - $periods = owa_lib::reporting_periods(); - - return $periods[$period]['label']; - } - - /** - * Assembles the current URL from request params - * - * @return string - */ - public static function get_current_url() { - - $url = 'http'; - - // check for https - if( isset( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) == 'on') { - $url.= 's'; - } elseif ( isset( $_SERVER['SERVER_PORT'] ) && $_SERVER['SERVER_PORT'] == 443 ) { - $url.= 's'; - } elseif ( isset( $_SERVER['HTTP_ORIGIN'] ) && substr( $_SERVER['HTTP_ORIGIN'], 0, 5 ) === 'https' ) { - $url.= 's'; - } elseif ( isset( $_SERVER['HTTP_REFERER'] ) && substr( $_SERVER['HTTP_REFERER'], 0, 5 ) === 'https' ) { - $url.= 's'; - } - - if ( isset( $_SERVER['HTTP_HOST'] ) ) { - // contains port number - $domain = $_SERVER['HTTP_HOST']; - } else { - // does not contain port number. - $domain = $_SERVER['SERVER_NAME']; - if( $_SERVER['SERVER_PORT'] != 80 ) { - $domain .= ':' . $_SERVER['SERVER_PORT']; - } - } - - $url .= '://'.$domain; - - $url .= $_SERVER['REQUEST_URI']; - - return $url; - } - - public static function inputFilter($input, $options = array() ) { - - return owa_sanitize::cleanInput( $input, $options ); - } - - public static function fileInclusionFilter($str) { - - $str = str_replace("http://", "", $str); - $str = str_replace("/", "", $str); - $str = str_replace("\\", "", $str); - $str = str_replace("../", "", $str); - $str = str_replace("..", "", $str); - $str = str_replace("?", "", $str); - $str = str_replace("%00", "", $str); - - if (strpos($str, '%00')) { - $str = ''; - } - - if ($str == null) { - $str = ''; - } - - return $str; - } - - /** - * Generic Factory method - * - * @param string $class_dir - * @param string $class_prefix - * @param string $class_name - * @param array $constructorArguments - * @return object - */ - public static function factory($class_dir, $class_prefix, $class_name, $constructorArguments = array(), $class_suffix = '') { - - $class_dir = $class_dir.'/'; - $classfile = $class_dir . $class_name . '.php'; - $class = $class_prefix . $class_name . $class_suffix; - - /* - * Attempt to include a version of the named class, but don't treat - * a failure as fatal. The caller may have already included their own - * version of the named class. - */ - if (!class_exists($class)) { - if (!file_exists($classfile)) { - throw new Exception('Class File '.$classfile.' not existend!'); - } - require_once ($classfile); - } - - if (!class_exists($class)) { - throw new Exception('Class '.$class.' not existend!'); - } - return new $class($constructorArguments); - } - - public static function simpleFactory( $class_name, $file_path = '', $args = '' ) { - - if ( ! class_exists( $class_name ) ) { - - if ( ! file_exists( $file_path ) ) { - throw new Exception("Factory cannot make $class_name becasue $file_path does not exist!"); - } else { - - require_once( $file_path ); - - } - - } - - if ( ! class_exists( $class_name ) ) { - - throw new Exception("Class $class_name still does not exist!"); - } - - return new $class_name( $args ); - } - - /** - * Generic Object Singleton - * - * @param string $class_dir - * @param string $class_prefix - * @param string $class_name - * @param array $conf - * @return object - */ - public static function singleton($class_dir, $class_prefix, $class_name, $conf = array()) { - - static $instance; - - if (!isset($instance)) { - // below missing a reference becasue the static vriable can not handle a reference - $instance = owa_lib::factory($class_dir, $class_prefix, $class_name, $conf); - } - - return $instance; - } - - /** - * 302 HTTP redirect the user to a new url - * - * @param string $url - */ - public static function redirectBrowser($url) { - //print ($url); exit; - // 302 redirect to URL - header ('Location: '.$url); - header ('HTTP/1.0 302 Found'); - } - - public static function makeLinkQueryString($query_params) { - - $new_query_params = array(); - - //Load params passed by caller - if (!empty($this->caller_params)): - foreach ($this->caller_params as $name => $value) { - if (!empty($value)): - $new_query_params[$name] = $value; - endif; - } - endif; - - // Load overrides - if (!empty($query_params)): - foreach ($query_params as $name => $value) { - if (!empty($value)): - $new_query_params[$name] = $value; - endif; - } - endif; - - // Construct GET request - if (!empty($new_query_params)): - foreach ($new_query_params as $name => $value) { - if (!empty($value)): - $get .= $name . "=" . $value . "&"; - endif; - } - endif; - - return $get; - - } - - public static function getRequestParams() { - - $params = array(); - - if (!empty($_POST)) { - $params = $_POST; - } else { - $params = $_GET; - } - - if (!empty($_COOKIE)) { - - $params = array_merge($params, $_COOKIE); - } - - return $params; - } - - public static function rekeyArray($array, $new_keys) { - - $new_keys = $new_keys; - $new_array = array(); - foreach ($array as $k => $v) { - - if (array_key_exists($k, $new_keys)) { - $k = $new_keys[$k]; - } - - $new_array[$k] = $v; - } - - return $new_array; - } - - - public static function stripParams($params, $ns = '') { - - $striped_params = array(); - - if (!empty($ns)) { - - $len = strlen($ns); - - foreach ($params as $n => $v) { - - // if namespace is present in param - if (strstr($n, $ns)) { - // strip the namespace value - $striped_n = substr($n, $len); - //add to striped array - $striped_params[$striped_n] = $v; - - } - - } - - return $striped_params; - - } else { - - return $params; - } - - } - - /** - * module specific require method - * - * @param unknown_type $module - * @param unknown_type $file - * @return unknown - * @deprecated - */ - public static function moduleRequireOnce($module, $file) { - - return require_once(OWA_BASE_DIR.'/modules/'.$module.'/'.$file.'.php'); - } - - /** - * module specific factory - * - * @param unknown_type $modulefile - * @param unknown_type $class_suffix - * @param unknown_type $params - * @return unknown - * @deprecated - */ - public static function moduleFactory($modulefile, $class_suffix = null, $params = '') { - - list($module, $file) = explode(".", $modulefile); - $class = 'owa_'.$file.$class_suffix; - - // Require class file if class does not already exist - if(!class_exists($class)): - owa_lib::moduleRequireOnce($module, $file); - endif; - - $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params); - $obj->module = $module; - - return $obj; - } - - /** - * redirects borwser to a particular view - * - * @param unknown_type $data - */ - public static function redirectToView($data) { - //print_r($data); - $c = owa_coreAPI::configSingleton(); - $config = $c->fetch('base'); - - $control_params = array('view_method', 'auth_status'); - - - $get = ''; - - foreach ($data as $n => $v) { - - if (!in_array($n, $control_params)) { - - $get .= $config['ns'].$n.'='.$v.'&'; - - } - } - - $new_url = sprintf($config['link_template'], $config['main_url'], $get); - - owa_lib::redirectBrowser($new_url); - } - - /** - * Displays a View without user authentication. Takes array of data as input - * - * @param array $data - * @deprecated - */ - public static function displayView($data, $params = array()) { - - $view = owa_lib::moduleFactory($data['view'], 'View', $params); - - return $view->assembleView($data); - - } - - /** - * Create guid from string - * - * @param string $string - * @return integer - * @access private - */ - public static function setStringGuid($string) { - - if ( $string ) { - - - if ( owa_coreAPI::getSetting('base', 'use_64bit_hash') && PHP_INT_MAX == '9223372036854775807') { - // make 64 bit ID from partial sha1 - return (string) (int) hexdec( substr( sha1( strtolower( $string ) ), 0, 16 ) ); - } else { - // make 32 bit ID from crc32 - return crc32( strtolower( $string ) ); - } - } - } - - /** - * Add constraints into SQL where clause - * - * @param array $constraints - * @return string $where - * @access public - * @depricated - * @todo remove - */ - function addConstraints($constraints) { - - if (!empty($constraints)): - - $count = count($constraints); - - $i = 0; - - $where = ''; - - foreach ($constraints as $key => $value) { - - if (empty($value)): - $i++; - else: - - if (!is_array($value)): - $where .= $key . ' = ' . "'$value'"; - else: - - switch ($value['operator']) { - case 'BETWEEN': - $where .= sprintf("%s BETWEEN '%s' AND '%s'", $key, $value['start'], $value['end']); - break; - default: - $where .= sprintf("%s %s '%s'", $key, $value['operator'], $value['value']); - break; - } - - - endif; - - if ($i < $count - 1): - - $where .= " AND "; - - endif; - - $i++; - - endif; - - } - // needed in case all values in the array are empty - if (!empty($where)): - return $where; - else: - return; - endif; - - else: - - return; - - endif; - - - - } - - public static function assocFromString($string_state, $inner = '=>', $outer = '|||') { - - if (!empty($string_state)): - - if (strpos($string_state, $outer) === false): - - return $string_state; - - else: - - $array = explode($outer, $string_state); - - $state = array(); - - foreach ($array as $key => $value) { - - list($realkey, $realvalue) = explode($inner, $value); - $state[$realkey] = $realvalue; - - } - - endif; - - endif; - - return $state; - - - } - - /** - * Simple function to replicate PHP 5 behaviour - */ - - public static function microtime_float() { - list($usec, $sec) = explode(" ", microtime()); - return ((float)$usec + (float)$sec); - } - - /** - * Lists all files in a Directory - * - */ - public static function listDir($start_dir='.', $recursive = true) { - - $files = array(); - - if (is_dir($start_dir)): - - $fh = opendir($start_dir); - - while (($file = readdir($fh)) !== false) { - - // loop through the files, skipping . and .., and recursing if necessary - if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue; - $filepath = $start_dir . '/' . $file; - - - if (is_dir($filepath)): - if ($recursive === true): - $files = array_merge($files, owa_lib::listDir($filepath)); - endif; - else: - array_push($files, array('name' => $file, 'path' => $filepath)); - endif; - } - - closedir($fh); - - else: - // false if the function was called with an invalid non-directory argument - $files = false; - endif; - - return $files; - - } - - public static function makeDateArray($result, $format) { - - if (!empty($result)) { - - $timestamps = array(); - - foreach ($result as $row) { - - $timestamps[]= mktime(0,0,0,$row['month'],$row['day'],$row['year']); - } - - return owa_lib::makeDates($timestamps, $format); - - } else { - - return array(); - } - - } - - public static function makeDates($timestamps, $format) { - - sort($timestamps); - - $new_dates = array(); - - foreach ($timestamps as $timestamp) { - - $new_dates[] = date($format, $timestamp); - - } - - return $new_dates; - - } - - public static function html2txt($document){ - $search = array('@]*?>.*?@si', // Strip out javascript - '@]*?>.*?@siU', // Strip style tags properly - '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags - '@@' // Strip multi-line comments including CDATA - ); - $text = preg_replace($search, '', $document); - return $text; - } - - public static function escapeNonAsciiChars($string) { - - return preg_replace('/[^(\x20-\x7F)]*/','', $string); - } - - /** - * Truncate string - * - * @param string $str - * @param integer $length - * @param string $trailing - * @return string - */ - public static function truncate ($str, $length=10, $trailing='...') { - - // take off chars for the trailing - $length-=strlen($trailing); - if (strlen($str) > $length): - // string exceeded length, truncate and add trailing dots - return substr($str,0,$length).$trailing; - else: - // string was already short enough, return the string - $res = $str; - endif; - - return $res; - } - - /** - * Simple Password Encryption - * - * @param string $password - * @return string - */ - public static function encryptOldPassword($password) { - - return md5(strtolower($password).strlen($password)); - //return owa_coreAPI::saltedHash( $password, 'auth'); - } - public static function encryptPassword($password) { - - // check function exists to support older PHP - if ( function_exists('password_hash') ) { - return password_hash( $password, PASSWORD_DEFAULT ); - } else { - return self::encryptOldPassword($password); - } - } - - public static function hash( $hash_type = 'md5', $data, $salt = '' ) { - - return hash_hmac( $hash_type, $data, $salt ); - } - - public static function timestampToYyyymmdd($timestamp = '') { - - if(empty($timestamp)) { - $timestamp = time(); - } - //print "before date"; - $yyyymmdd = date("Ymd", $timestamp); - ///print "after date"; - return $yyyymmdd; - } - - public static function setContentTypeHeader($type = 'html') { - - if (!$type) { - $type = 'html'; - } - - $content_types = array('html' => 'text/html', - 'xml' => 'text/xml', - 'json' => 'application/json', - 'jsonp' => 'application/json', - 'csv' => 'text/csv'); - - if (array_key_exists($type, $content_types)) { - $mime = $content_types[$type]; - header('Content-type: '.$mime); - } - } - - public static function array_values_assoc($assoc) { - - $values = array(); - - foreach ($assoc as $k => $v) { - - if (!empty($v)) { - $values[] = $v; - } - } - - return $values; - } - - public static function prepareCurrencyValue($string) { - - return $string * 100; - } - - public static function utf8Encode($string) { - - if ( owa_lib::checkForUtf8( $string ) ) { - return $string; - } else { - if (function_exists('iconv')) { - return iconv('UTF-8','UTF-8//TRANSLIT', $string); - } else { - // at least worth a try - return utf8_encode($string); - } - } - } - - public static function checkForUtf8($str) { - - if ( function_exists( 'mb_detect_encoding' ) ) { - $cur_encoding = mb_detect_encoding( $str ) ; - if ( $cur_encoding == "UTF-8" && mb_check_encoding( $str,"UTF-8" ) ) { - return true; - } - } else { - - $len = strlen( $str ); - for( $i = 0; $i < $len; $i++ ) { - - $c = ord( $str[$i] ); - if ($c > 128) { - - if ( ( $c > 247 ) ) { - return false; - } elseif ( $c > 239 ) { - $bytes = 4; - } elseif ( $c > 223 ) { - $bytes = 3; - } elseif ( $c > 191 ) { - $bytes = 2; - } else { - return false; - } - - if ( ( $i + $bytes ) > $len ) { - return false; - } - - while ( $bytes > 1 ) { - $i++; - $b = ord( $str[$i] ); - if ( $b < 128 || $b > 191 ) { - return false; - } - $bytes--; - } - } - } - return true; - } - } - - public static function formatCurrency($value, $local, $currency) { - - $value = $value / 100; - - if ( function_exists('numfmt_create') ) { - - $numberFormatter = new NumberFormatter($local, NumberFormatter::CURRENCY); - return $numberFormatter->formatCurrency($value, $currency); - - } else { - - setlocale( LC_MONETARY, $local ); - return money_format( '%.' . 2 . 'n',$value ); - } - } - - public static function crc32AsHex($string) { - $crc = crc32($string); - //$crc += 0x100000000; - if ($crc < 0) { - $crc = 0xFFFFFFFF + $crc + 1; - } - return dechex($crc); - } - - public static function getLocalTimestamp($utc = '') { - - if ( ! $utc ) { - $utc = time(); - } - $local_timezone_offset = date('Z'); - $daylight_savings = date('I') * 3600; - $local_time = $utc - $local_timezone_offset + $daylight_savings; - return $local_time; - } - - public static function sanitizeCookieDomain($domain) { - - // Remove port information. - $port = strpos( $domain, ':' ); - if ( $port ) { - $domain = substr( $domain, 0, $port ); - } - - // check for leading period, add if missing - $period = substr( $domain, 0, 1); - if ( $period != '.' ) { - $domain = '.'.$domain; - } - - return $domain; - } - - public static function stripWWWFromDomain($domain) { - - $done = false; - $part = substr( $domain, 0, 5 ); - if ($part === '.www.') { - //strip .www. - $domain = substr( $domain, 5); - // add back the leading period - $domain = '.'.$domain; - $done = true; - } - - if ( ! $done ) { - $part = substr( $domain, 0, 4 ); - if ($part === 'www.') { - //strip .www. - $domain = substr( $domain, 4); - $done = true; - } - - } - - return $domain; - } - - /** - * Use this function to parse out the url and query array element from - * a url. - */ - public static function parse_url( $url ) { - - $url = parse_url($url); - - if ( isset( $url['query'] ) ) { - $var = $url['query']; - - $var = html_entity_decode($var); - $var = explode('&', $var); - $arr = array(); - - foreach( $var as $val ) { - - if ( strpos($val, '=') ) { - $x = explode('=', $val); - - if ( isset( $x[1] ) ) { - $arr[$x[0]] = urldecode($x[1]); - } - } else { - $arr[$val] = ''; - } - } - unset($val, $x, $var); - - $url['query_params'] = $arr; - - } - - return $url; - } - - public static function iniGet( $name ) { - - $b = ini_get( $name ); - - switch ( strtolower( $b ) ) { - case 'on': - case 'yes': - case 'true': - return true; - - default: - return (bool) (int) $b; - } - - } - - // better empty check when you need to accept these as valid, non-empty values: - // - 0 (0 as an integer) - //- 0.0 (0 as a float) - //- "0" (0 as a string) - public static function isEmpty($value) { - - return empty($value) && ! is_numeric($value); - } - - public static function isIpAddressValid( $ip = '' ) { - - if ( $ip && filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { - // it's valid - return true; - } else { - // it's not valid - return false; - } - } - - public static function zeroFill( $number, $char_length ) { - - return str_pad( (int) $number, $char_length, "0", STR_PAD_LEFT ); - } - - public static function generateRandomUid($seed='') { - - $time = (string) time(); - $random = owa_lib::zeroFill( mt_rand( 0, 999999 ), 6 ); - if ( defined('OWA_SERVER_ID') ) { - $server = owa_lib::zeroFill( OWA_SERVER_ID, 3 ); - } else { - $server = substr( getmypid(), 0, 3); - } - - return $time.$random.$server; - } - - public static function unparseUrl($parsed_url, $ommit = array() ) { - - $url = ''; - $p = array(); - - $p['scheme'] = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; - $p['host'] = isset($parsed_url['host']) ? $parsed_url['host'] : ''; - $p['port'] = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; - $p['user'] = isset($parsed_url['user']) ? $parsed_url['user'] : ''; - $p['pass'] = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; - $p['pass'] = ( $p['user'] || $p['pass'] ) ? $p['pass']."@" : ''; - $p['path'] = isset($parsed_url['path']) ? $parsed_url['path'] : ''; - $p['query'] = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; - $p['fragment'] = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; - - if ( $ommit ) { - foreach ( $ommit as $key ) { - if ( isset( $p[ $key ] ) ) { - $p[ $key ] = ''; - } - } - } - - return $p['scheme'].$p['user'].$p['pass'].$p['host'].$p['port'].$p['path'].$p['query'].$p['fragment']; - } - - public static function moveFile( $oldfile, $newfile ) { - - if ( file_exists( $oldfile ) ) { - - if ( ! rename( $oldfile, $newfile ) ) { - - if ( copy( $oldfile, $newfile ) ) { - - unlink( $oldfile ); - - return true; - } - - } else { - - return true; - } - } - } - - public static function isValidIp( $ip_address ) { - - // if valid ip address - if ( ! empty( $ip_address ) - && ip2long( $ip_address ) != -1 - && ip2long( $ip_address ) != false - ) { - - return true; - } - - } - - // check to see if the IP address falls within known private IP ranges - public static function isPrivateIp( $ip_address ) { - - $ip = ip2long( $ip_address); - - $private_ip_ranges = array ( - array('0.0.0.0','2.255.255.255'), - array('10.0.0.0','10.255.255.255'), - array('127.0.0.0','127.255.255.255'), - array('169.254.0.0','169.254.255.255'), - array('172.16.0.0','172.31.255.255'), - array('192.0.2.0','192.0.2.255'), - array('192.168.0.0','192.168.255.255'), - array('255.255.255.0','255.255.255.255') - ); - - //check to see if it falls within a known private range - foreach ( $private_ip_ranges as $range ) { - - $min = ip2long( $range[0] ); - $max = ip2long( $range[1] ); - - if ( ( $ip >= $min ) && ( $ip <= $max ) ) { - - return true; - } - } - - // if it makes it through the checks then it's not private. - return false; - } -} - -?> + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_lib { + + /** + * Convert Associative Array to String + * + * @param string $inner_glue + * @param string $outer_glue + * @param array $array + * @return string + */ + public static function implode_assoc($inner_glue, $outer_glue, $array) { + $output = array(); + foreach( $array as $key => $item ) { + $output[] = $key . $inner_glue . $item; + } + + return implode($outer_glue, $output); + } + + /** + * Deconstruct Associative Array + * + * For example this takes array([1] => array(a => dog, b => cat), [2] => array(a => sheep, b => goat)) + * and tunrs it into array([a] => array(dog, sheep), [b] => array(cat, goat)) + * + * @param array $a_array + * @return array $data_arrays + * @access public + */ + public static function deconstruct_assoc($a_array) { + if (!empty($a_array)): + + $data_arrays = array(); + + if(!empty($a_array[1])) : + + foreach ($a_array as $key => $value) { + foreach ($value as $k => $v) { + $data_arrays[$k][] = $v; + + } + } + else: + //print_r($a_array[0]); + foreach ($a_array[0] as $key => $value) { + $data_arrays[$key][] = $value; + } + endif; + + return $data_arrays; + else: + return array(); + endif; + } + + + public static function decon_assoc($a_array) { + + $data_arrays = array(); + + foreach ($a_array as $key => $value) { + //foreach ($value as $k => $v) { + $data_arrays[$key][] = $value; + + //} + } + + return $data_arrays; + } + + // php 4 compatible function + public static function array_intersect_key() { + + $arrs = func_get_args(); + $result = array_shift($arrs); + foreach ($arrs as $array) { + foreach ($result as $key => $v) { + if (!array_key_exists($key, $array)) { + unset($result[$key]); + } + } + } + return $result; + } + + // php4 compatible function + public static function array_walk_recursive(&$input, $funcname, $userdata = "") + { + if (!is_callable($funcname)) + { + return false; + } + + if (!is_array($input)) + { + return false; + } + + if (is_array($funcname)) + { + $funcname = $funcname[0].'::'.$funcname[1]; + } + + + foreach ($input AS $key => $value) + { + if (is_array($input[$key])) + { + array_walk_recursive($input[$key], $funcname, $userdata); + } + else + { + $saved_value = $value; + if (!empty($userdata)) + { + $funcname($value, $key, $userdata); + } + else + { + $funcname($value, $key); + } + + if ($value != $saved_value) + { + $input[$key] = $value; + } + } + } + return true; + } + + /** + * Array of Current Time + * + * @return array + * @access public + */ + public static function time_now() { + + $timestamp = time(); + + return array( + + 'year' => date("Y", $timestamp), + 'month' => date("n", $timestamp), + 'day' => date("d", $timestamp), + 'dayofweek' => date("w", $timestamp), + 'dayofyear' => date("z", $timestamp), + 'weekofyear' => date("W", $timestamp), + 'hour' => date("G", $timestamp), + 'minute' => date("i", $timestamp), + 'second' => date("s", $timestamp), + 'timestamp' => $timestamp + ); + } + + /** + * Error Handler + * + * @param string $msg + * @access public + * @depricated + */ + function errorHandler($msg) { + require_once(OWA_PEARLOG_DIR . '/Log.php'); + $conf = array('mode' => 0755, 'timeFormat' => '%X %x'); + $error_logger = &Log::singleton('file', $this->config['error_log_file'], 'ident', $conf); + $this->error_logger->_lineFormat = '[%3$s]'; + + return; + } + + /** + * Information array for Months in the year. + * + * @return array + */ + public static function months() { + + return array( + + 1 => array('label' => 'January'), + 2 => array('label' => 'February'), + 3 => array('label' => 'March'), + 4 => array('label' => 'April'), + 5 => array('label' => 'May'), + 6 => array('label' => 'June'), + 7 => array('label' => 'July'), + 8 => array('label' => 'August'), + 9 => array('label' => 'September'), + 10 => array('label' => 'October'), + 11 => array('label' => 'November'), + 12 => array('label' => 'December') + ); + + } + + public static function days() { + + return array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31); + } + + public static function years() { + + static $years; + + if (empty($years)): + + $start_year = 2005; + + $years = array($start_year); + + $num_years = date("Y", time()) - $start_year; + + for($i=1; $i<=$num_years; $i++) { + + $years[] = $start_year + $i; + } + + $years = array_reverse($years); + + endif; + + return $years; + } + + + /** + * Returns a label from an array of months + * + * @param int $month + * @return string + */ + public static function get_month_label($month) { + + static $months; + + if (empty($months)): + + $months = owa_lib::months(); + + endif; + + return $months[$month]['label']; + + } + + + /** + * Sets the suffix for Days used in Date labels + * @depricated + * @param string $day + * @return string + */ + public static function setDaySuffix($day) { + + switch ($day) { + + case "1": + $day_suffix = 'st'; + break; + case "2": + $day_suffix = 'nd'; + break; + case "3": + $day_suffix = 'rd'; + break; + default: + $day_suffix = 'th'; + } + + return $day_suffix; + + } + + /** + * Generates the label for a date + * @depricated + * @param array $params + * @return string + */ + public static function getDatelabel($params) { + + switch ($params['period']) { + + case "day": + return sprintf("%s, %d%s %s", + owa_lib::get_month_label($params['month']), + $params['day'], + owa_lib::setDaySuffix($params['day']), + $params['year'] + ); + break; + + case "month": + return sprintf("%s %s", + owa_lib::get_month_label($params['month']), + $params['year'] + ); + break; + + case "year": + return sprintf("%s", + $params['year'] + ); + break; + case "date_range": + return sprintf("%s, %d%s %s - %s, %d%s %s", + owa_lib::get_month_label($params['month']), + $params['day'], + owa_lib::setDaySuffix($params['day']), + $params['year'], + owa_lib::get_month_label($params['month2']), + $params['day2'], + owa_lib::setDaySuffix($params['day2']), + $params['year2'] + ); + break; + } + + return false; + + } + + /** + * Array of Reporting Periods + * @depricated + * @return array + */ + public static function reporting_periods() { + + return array( + + 'today' => array('label' => 'Today'), + 'yesterday' => array('label' => 'Yesterday'), + 'this_week' => array('label' => 'This Week'), + 'this_month' => array('label' => 'This Month'), + 'this_year' => array('label' => 'This Year'), + 'last_week' => array('label' => 'Last Week'), + 'last_month' => array('label' => 'Last Month'), + 'last_year' => array('label' => 'Last Year'), + 'last_half_hour' => array('label' => 'The Last 30 Minutes'), + 'last_hour' => array('label' => 'Last Hour'), + 'last_24_hours' => array('label' => 'The Last 24 Hours'), + 'last_seven_days' => array('label' => 'The Last Seven Days'), + 'last_thirty_days' => array('label' => 'The Last Thirty Days'), + 'same_day_last_week' => array('label' => 'Same Day last Week'), + 'same_week_last_year' => array('label' => 'Same Week Last Year'), + 'same_month_last_year' => array('label' => 'Same Month Last Year'), + 'date_range' => array('label' => 'Date Range') + ); + + } + + /** + * Array of Date specific Reporting Periods + * @depricated + * @return array + */ + public static function date_reporting_periods() { + + return array( + + 'day' => array('label' => 'Day'), + 'month' => array('label' => 'Month'), + 'year' => array('label' => 'Year'), + 'date_range' => array('label' => 'Date Range') + ); + + } + + /** + * Gets label for a particular reporting period + * + * @param unknown_type $period + * @return unknown + */ + public static function get_period_label($period) { + + $periods = owa_lib::reporting_periods(); + + return $periods[$period]['label']; + } + + /** + * Assembles the current URL from request params + * + * @return string + */ + public static function get_current_url() { + + $url = 'http'; + + // check for https + if( isset( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) == 'on') { + $url.= 's'; + } elseif ( isset( $_SERVER['SERVER_PORT'] ) && $_SERVER['SERVER_PORT'] == 443 ) { + $url.= 's'; + } elseif ( isset( $_SERVER['HTTP_ORIGIN'] ) && substr( $_SERVER['HTTP_ORIGIN'], 0, 5 ) === 'https' ) { + $url.= 's'; + } elseif ( isset( $_SERVER['HTTP_REFERER'] ) && substr( $_SERVER['HTTP_REFERER'], 0, 5 ) === 'https' ) { + $url.= 's'; + } + + if ( isset( $_SERVER['HTTP_HOST'] ) ) { + // contains port number + $domain = $_SERVER['HTTP_HOST']; + } else { + // does not contain port number. + $domain = $_SERVER['SERVER_NAME']; + if( $_SERVER['SERVER_PORT'] != 80 ) { + $domain .= ':' . $_SERVER['SERVER_PORT']; + } + } + + $url .= '://'.$domain; + + $url .= $_SERVER['REQUEST_URI']; + + return $url; + } + + public static function inputFilter($input, $options = array() ) { + + return owa_sanitize::cleanInput( $input, $options ); + } + + public static function fileInclusionFilter($str) { + + $str = str_replace("http://", "", $str); + $str = str_replace("/", "", $str); + $str = str_replace("\\", "", $str); + $str = str_replace("../", "", $str); + $str = str_replace("..", "", $str); + $str = str_replace("?", "", $str); + $str = str_replace("%00", "", $str); + + if (strpos($str, '%00')) { + $str = ''; + } + + if ($str == null) { + $str = ''; + } + + return $str; + } + + /** + * Generic Factory method + * + * @param string $class_dir + * @param string $class_prefix + * @param string $class_name + * @param array $constructorArguments + * @return object + */ + public static function factory($class_dir, $class_prefix, $class_name, $constructorArguments = array(), $class_suffix = '') { + + $class_dir = $class_dir.'/'; + $classfile = $class_dir . $class_name . '.php'; + $class = $class_prefix . $class_name . $class_suffix; + + /* + * Attempt to include a version of the named class, but don't treat + * a failure as fatal. The caller may have already included their own + * version of the named class. + */ + if (!class_exists($class)) { + if (!file_exists($classfile)) { + throw new Exception('Class File '.$classfile.' not existend!'); + } + require_once ($classfile); + } + + if (!class_exists($class)) { + throw new Exception('Class '.$class.' not existend!'); + } + return new $class($constructorArguments); + } + + public static function simpleFactory( $class_name, $file_path = '', $args = '' ) { + + if ( ! class_exists( $class_name ) ) { + + if ( ! file_exists( $file_path ) ) { + throw new Exception("Factory cannot make $class_name becasue $file_path does not exist!"); + } else { + + require_once( $file_path ); + + } + + } + + if ( ! class_exists( $class_name ) ) { + + throw new Exception("Class $class_name still does not exist!"); + } + + return new $class_name( $args ); + } + + /** + * Generic Object Singleton + * + * @param string $class_dir + * @param string $class_prefix + * @param string $class_name + * @param array $conf + * @return object + */ + public static function singleton($class_dir, $class_prefix, $class_name, $conf = array()) { + + static $instance; + + if (!isset($instance)) { + // below missing a reference becasue the static vriable can not handle a reference + $instance = owa_lib::factory($class_dir, $class_prefix, $class_name, $conf); + } + + return $instance; + } + + /** + * 302 HTTP redirect the user to a new url + * + * @param string $url + */ + public static function redirectBrowser($url) { + //print ($url); exit; + // 302 redirect to URL + header ('Location: '.$url); + header ('HTTP/1.0 302 Found'); + } + + public static function makeLinkQueryString($query_params) { + + $new_query_params = array(); + + //Load params passed by caller + if (!empty($this->caller_params)): + foreach ($this->caller_params as $name => $value) { + if (!empty($value)): + $new_query_params[$name] = $value; + endif; + } + endif; + + // Load overrides + if (!empty($query_params)): + foreach ($query_params as $name => $value) { + if (!empty($value)): + $new_query_params[$name] = $value; + endif; + } + endif; + + // Construct GET request + if (!empty($new_query_params)): + foreach ($new_query_params as $name => $value) { + if (!empty($value)): + $get .= $name . "=" . $value . "&"; + endif; + } + endif; + + return $get; + + } + + public static function getRequestParams() { + + $params = array(); + + if (!empty($_POST)) { + $params = $_POST; + } else { + $params = $_GET; + } + + if (!empty($_COOKIE)) { + + $params = array_merge($params, $_COOKIE); + } + + return $params; + } + + public static function rekeyArray($array, $new_keys) { + + $new_keys = $new_keys; + $new_array = array(); + foreach ($array as $k => $v) { + + if (array_key_exists($k, $new_keys)) { + $k = $new_keys[$k]; + } + + $new_array[$k] = $v; + } + + return $new_array; + } + + + public static function stripParams($params, $ns = '') { + + $striped_params = array(); + + if (!empty($ns)) { + + $len = strlen($ns); + + foreach ($params as $n => $v) { + + // if namespace is present in param + if (strstr($n, $ns)) { + // strip the namespace value + $striped_n = substr($n, $len); + //add to striped array + $striped_params[$striped_n] = $v; + + } + + } + + return $striped_params; + + } else { + + return $params; + } + + } + + /** + * module specific require method + * + * @param unknown_type $module + * @param unknown_type $file + * @return unknown + * @deprecated + */ + public static function moduleRequireOnce($module, $file) { + + return require_once(OWA_BASE_DIR.'/modules/'.$module.'/'.$file.'.php'); + } + + /** + * module specific factory + * + * @param unknown_type $modulefile + * @param unknown_type $class_suffix + * @param unknown_type $params + * @return unknown + * @deprecated + */ + public static function moduleFactory($modulefile, $class_suffix = null, $params = '') { + + list($module, $file) = explode(".", $modulefile); + $class = 'owa_'.$file.$class_suffix; + + // Require class file if class does not already exist + if(!class_exists($class)): + owa_lib::moduleRequireOnce($module, $file); + endif; + + $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params); + $obj->module = $module; + + return $obj; + } + + /** + * redirects borwser to a particular view + * + * @param unknown_type $data + */ + public static function redirectToView($data) { + //print_r($data); + $c = owa_coreAPI::configSingleton(); + $config = $c->fetch('base'); + + $control_params = array('view_method', 'auth_status'); + + + $get = ''; + + foreach ($data as $n => $v) { + + if (!in_array($n, $control_params)) { + + $get .= $config['ns'].$n.'='.$v.'&'; + + } + } + + $new_url = sprintf($config['link_template'], $config['main_url'], $get); + + owa_lib::redirectBrowser($new_url); + } + + /** + * Displays a View without user authentication. Takes array of data as input + * + * @param array $data + * @deprecated + */ + public static function displayView($data, $params = array()) { + + $view = owa_lib::moduleFactory($data['view'], 'View', $params); + + return $view->assembleView($data); + + } + + /** + * Create guid from string + * + * @param string $string + * @return integer + * @access private + */ + public static function setStringGuid($string) { + + if ( $string ) { + + + if ( owa_coreAPI::getSetting('base', 'use_64bit_hash') && PHP_INT_MAX == '9223372036854775807') { + // make 64 bit ID from partial sha1 + return (string) (int) hexdec( substr( sha1( strtolower( $string ) ), 0, 16 ) ); + } else { + // make 32 bit ID from crc32 + return crc32( strtolower( $string ) ); + } + } + } + + /** + * Add constraints into SQL where clause + * + * @param array $constraints + * @return string $where + * @access public + * @depricated + * @todo remove + */ + function addConstraints($constraints) { + + if (!empty($constraints)): + + $count = count($constraints); + + $i = 0; + + $where = ''; + + foreach ($constraints as $key => $value) { + + if (empty($value)): + $i++; + else: + + if (!is_array($value)): + $where .= $key . ' = ' . "'$value'"; + else: + + switch ($value['operator']) { + case 'BETWEEN': + $where .= sprintf("%s BETWEEN '%s' AND '%s'", $key, $value['start'], $value['end']); + break; + default: + $where .= sprintf("%s %s '%s'", $key, $value['operator'], $value['value']); + break; + } + + + endif; + + if ($i < $count - 1): + + $where .= " AND "; + + endif; + + $i++; + + endif; + + } + // needed in case all values in the array are empty + if (!empty($where)): + return $where; + else: + return; + endif; + + else: + + return; + + endif; + + + + } + + public static function assocFromString($string_state, $inner = '=>', $outer = '|||') { + + if (!empty($string_state)): + + if (strpos($string_state, $outer) === false): + + return $string_state; + + else: + + $array = explode($outer, $string_state); + + $state = array(); + + foreach ($array as $key => $value) { + + list($realkey, $realvalue) = explode($inner, $value); + $state[$realkey] = $realvalue; + + } + + endif; + + endif; + + return $state; + + + } + + /** + * Simple function to replicate PHP 5 behaviour + */ + + public static function microtime_float() { + list($usec, $sec) = explode(" ", microtime()); + return ((float)$usec + (float)$sec); + } + + /** + * Lists all files in a Directory + * + */ + public static function listDir($start_dir='.', $recursive = true) { + + $files = array(); + + if (is_dir($start_dir)): + + $fh = opendir($start_dir); + + while (($file = readdir($fh)) !== false) { + + // loop through the files, skipping . and .., and recursing if necessary + if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue; + $filepath = $start_dir . '/' . $file; + + + if (is_dir($filepath)): + if ($recursive === true): + $files = array_merge($files, owa_lib::listDir($filepath)); + endif; + else: + array_push($files, array('name' => $file, 'path' => $filepath)); + endif; + } + + closedir($fh); + + else: + // false if the function was called with an invalid non-directory argument + $files = false; + endif; + + return $files; + + } + + public static function makeDateArray($result, $format) { + + if (!empty($result)) { + + $timestamps = array(); + + foreach ($result as $row) { + + $timestamps[]= mktime(0,0,0,$row['month'],$row['day'],$row['year']); + } + + return owa_lib::makeDates($timestamps, $format); + + } else { + + return array(); + } + + } + + public static function makeDates($timestamps, $format) { + + sort($timestamps); + + $new_dates = array(); + + foreach ($timestamps as $timestamp) { + + $new_dates[] = date($format, $timestamp); + + } + + return $new_dates; + + } + + public static function html2txt($document){ + $search = array('@]*?>.*?@si', // Strip out javascript + '@]*?>.*?@siU', // Strip style tags properly + '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags + '@@' // Strip multi-line comments including CDATA + ); + $text = preg_replace($search, '', $document); + return $text; + } + + public static function escapeNonAsciiChars($string) { + + return preg_replace('/[^(\x20-\x7F)]*/','', $string); + } + + /** + * Truncate string + * + * @param string $str + * @param integer $length + * @param string $trailing + * @return string + */ + public static function truncate ($str, $length=10, $trailing='...') { + + // take off chars for the trailing + $length-=strlen($trailing); + if (strlen($str) > $length): + // string exceeded length, truncate and add trailing dots + return substr($str,0,$length).$trailing; + else: + // string was already short enough, return the string + $res = $str; + endif; + + return $res; + } + + /** + * Simple Password Encryption + * + * @param string $password + * @return string + */ + public static function encryptOldPassword($password) { + + return md5(strtolower($password).strlen($password)); + //return owa_coreAPI::saltedHash( $password, 'auth'); + } + public static function encryptPassword($password) { + + // check function exists to support older PHP + if ( function_exists('password_hash') ) { + return password_hash( $password, PASSWORD_DEFAULT ); + } else { + return self::encryptOldPassword($password); + } + } + + public static function hash( $hash_type = 'md5', $data, $salt = '' ) { + + return hash_hmac( $hash_type, $data, $salt ); + } + + public static function timestampToYyyymmdd($timestamp = '') { + + if(empty($timestamp)) { + $timestamp = time(); + } + //print "before date"; + $yyyymmdd = date("Ymd", $timestamp); + ///print "after date"; + return $yyyymmdd; + } + + public static function setContentTypeHeader($type = 'html') { + + if (!$type) { + $type = 'html'; + } + + $content_types = array('html' => 'text/html', + 'xml' => 'text/xml', + 'json' => 'application/json', + 'jsonp' => 'application/json', + 'csv' => 'text/csv'); + + if (array_key_exists($type, $content_types)) { + $mime = $content_types[$type]; + header('Content-type: '.$mime); + } + } + + public static function array_values_assoc($assoc) { + + $values = array(); + + foreach ($assoc as $k => $v) { + + if (!empty($v)) { + $values[] = $v; + } + } + + return $values; + } + + public static function prepareCurrencyValue($string) { + + return $string * 100; + } + + public static function utf8Encode($string) { + + if ( owa_lib::checkForUtf8( $string ) ) { + return $string; + } else { + if (function_exists('iconv')) { + return iconv('UTF-8','UTF-8//TRANSLIT', $string); + } else { + // at least worth a try + return utf8_encode($string); + } + } + } + + public static function checkForUtf8($str) { + + if ( function_exists( 'mb_detect_encoding' ) ) { + $cur_encoding = mb_detect_encoding( $str ) ; + if ( $cur_encoding == "UTF-8" && mb_check_encoding( $str,"UTF-8" ) ) { + return true; + } + } else { + + $len = strlen( $str ); + for( $i = 0; $i < $len; $i++ ) { + + $c = ord( $str[$i] ); + if ($c > 128) { + + if ( ( $c > 247 ) ) { + return false; + } elseif ( $c > 239 ) { + $bytes = 4; + } elseif ( $c > 223 ) { + $bytes = 3; + } elseif ( $c > 191 ) { + $bytes = 2; + } else { + return false; + } + + if ( ( $i + $bytes ) > $len ) { + return false; + } + + while ( $bytes > 1 ) { + $i++; + $b = ord( $str[$i] ); + if ( $b < 128 || $b > 191 ) { + return false; + } + $bytes--; + } + } + } + return true; + } + } + + public static function formatCurrency($value, $local, $currency) { + + $value = $value / 100; + + if ( function_exists('numfmt_create') ) { + + $numberFormatter = new NumberFormatter($local, NumberFormatter::CURRENCY); + return $numberFormatter->formatCurrency($value, $currency); + + } else { + + setlocale( LC_MONETARY, $local ); + return money_format( '%.' . 2 . 'n',$value ); + } + } + + public static function crc32AsHex($string) { + $crc = crc32($string); + //$crc += 0x100000000; + if ($crc < 0) { + $crc = 0xFFFFFFFF + $crc + 1; + } + return dechex($crc); + } + + public static function getLocalTimestamp($utc = '') { + + if ( ! $utc ) { + $utc = time(); + } + $local_timezone_offset = date('Z'); + $daylight_savings = date('I') * 3600; + $local_time = $utc - $local_timezone_offset + $daylight_savings; + return $local_time; + } + + public static function sanitizeCookieDomain($domain) { + + // Remove port information. + $port = strpos( $domain, ':' ); + if ( $port ) { + $domain = substr( $domain, 0, $port ); + } + + // check for leading period, add if missing + $period = substr( $domain, 0, 1); + if ( $period != '.' ) { + $domain = '.'.$domain; + } + + return $domain; + } + + public static function stripWWWFromDomain($domain) { + + $done = false; + $part = substr( $domain, 0, 5 ); + if ($part === '.www.') { + //strip .www. + $domain = substr( $domain, 5); + // add back the leading period + $domain = '.'.$domain; + $done = true; + } + + if ( ! $done ) { + $part = substr( $domain, 0, 4 ); + if ($part === 'www.') { + //strip .www. + $domain = substr( $domain, 4); + $done = true; + } + + } + + return $domain; + } + + /** + * Use this function to parse out the url and query array element from + * a url. + */ + public static function parse_url( $url ) { + + $url = parse_url($url); + + if ( isset( $url['query'] ) ) { + $var = $url['query']; + + $var = html_entity_decode($var); + $var = explode('&', $var); + $arr = array(); + + foreach( $var as $val ) { + + if ( strpos($val, '=') ) { + $x = explode('=', $val); + + if ( isset( $x[1] ) ) { + $arr[$x[0]] = urldecode($x[1]); + } + } else { + $arr[$val] = ''; + } + } + unset($val, $x, $var); + + $url['query_params'] = $arr; + + } + + return $url; + } + + public static function iniGet( $name ) { + + $b = ini_get( $name ); + + switch ( strtolower( $b ) ) { + case 'on': + case 'yes': + case 'true': + return true; + + default: + return (bool) (int) $b; + } + + } + + // better empty check when you need to accept these as valid, non-empty values: + // - 0 (0 as an integer) + //- 0.0 (0 as a float) + //- "0" (0 as a string) + public static function isEmpty($value) { + + return empty($value) && ! is_numeric($value); + } + + public static function isIpAddressValid( $ip = '' ) { + + if ( $ip && filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { + // it's valid + return true; + } else { + // it's not valid + return false; + } + } + + public static function zeroFill( $number, $char_length ) { + + return str_pad( (int) $number, $char_length, "0", STR_PAD_LEFT ); + } + + public static function generateRandomUid($seed='') { + + $time = (string) time(); + $random = owa_lib::zeroFill( mt_rand( 0, 999999 ), 6 ); + if ( defined('OWA_SERVER_ID') ) { + $server = owa_lib::zeroFill( OWA_SERVER_ID, 3 ); + } else { + $server = substr( getmypid(), 0, 3); + } + + return $time.$random.$server; + } + + public static function unparseUrl($parsed_url, $ommit = array() ) { + + $url = ''; + $p = array(); + + $p['scheme'] = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; + $p['host'] = isset($parsed_url['host']) ? $parsed_url['host'] : ''; + $p['port'] = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; + $p['user'] = isset($parsed_url['user']) ? $parsed_url['user'] : ''; + $p['pass'] = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; + $p['pass'] = ( $p['user'] || $p['pass'] ) ? $p['pass']."@" : ''; + $p['path'] = isset($parsed_url['path']) ? $parsed_url['path'] : ''; + $p['query'] = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; + $p['fragment'] = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; + + if ( $ommit ) { + foreach ( $ommit as $key ) { + if ( isset( $p[ $key ] ) ) { + $p[ $key ] = ''; + } + } + } + + return $p['scheme'].$p['user'].$p['pass'].$p['host'].$p['port'].$p['path'].$p['query'].$p['fragment']; + } + + public static function moveFile( $oldfile, $newfile ) { + + if ( file_exists( $oldfile ) ) { + + if ( ! rename( $oldfile, $newfile ) ) { + + if ( copy( $oldfile, $newfile ) ) { + + unlink( $oldfile ); + + return true; + } + + } else { + + return true; + } + } + } + + public static function isValidIp( $ip_address ) { + + // if valid ip address + if ( ! empty( $ip_address ) + && ip2long( $ip_address ) != -1 + && ip2long( $ip_address ) != false + ) { + + return true; + } + + } + + // check to see if the IP address falls within known private IP ranges + public static function isPrivateIp( $ip_address ) { + + $ip = ip2long( $ip_address); + + $private_ip_ranges = array ( + array('0.0.0.0','2.255.255.255'), + array('10.0.0.0','10.255.255.255'), + array('127.0.0.0','127.255.255.255'), + array('169.254.0.0','169.254.255.255'), + array('172.16.0.0','172.31.255.255'), + array('192.0.2.0','192.0.2.255'), + array('192.168.0.0','192.168.255.255'), + array('255.255.255.0','255.255.255.255') + ); + + //check to see if it falls within a known private range + foreach ( $private_ip_ranges as $range ) { + + $min = ip2long( $range[0] ); + $max = ip2long( $range[1] ); + + if ( ( $ip >= $min ) && ( $ip <= $max ) ) { + + return true; + } + } + + // if it makes it through the checks then it's not private. + return false; + } +} + +?> diff --git a/owa_location.php b/owa_location.php index 4a868355b..0413af98b 100644 --- a/owa_location.php +++ b/owa_location.php @@ -1,80 +1,80 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_location { - - /** - * City - * - * @var string - */ - var $city; - - /** - * Country - * - * @var string - */ - var $country; - - /** - * Latitude coordinates - * - * @var string - */ - var $latitude; - - /** - * Longitude coordinates - * - * @var string - */ - var $longitude; - - /** - * Location of concrete class plugins - * - * @var unknown_type - */ - var $plugin_dir; - - /** - * Constructor - * - * @return owa_location - */ - function __construct() { - - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_location { + + /** + * City + * + * @var string + */ + var $city; + + /** + * Country + * + * @var string + */ + var $country; + + /** + * Latitude coordinates + * + * @var string + */ + var $latitude; + + /** + * Longitude coordinates + * + * @var string + */ + var $longitude; + + /** + * Location of concrete class plugins + * + * @var unknown_type + */ + var $plugin_dir; + + /** + * Constructor + * + * @return owa_location + */ + function __construct() { + + } +} + ?> \ No newline at end of file diff --git a/owa_metric.php b/owa_metric.php index a25000f65..8e1229b41 100644 --- a/owa_metric.php +++ b/owa_metric.php @@ -1,363 +1,363 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ -class owa_metric extends owa_base { - - /** - * Current Time - * - * @var array - */ - var $time_now = array(); - - /** - * Data - * - * @var array - */ - var $data; - - /** - * The params of the caller, either a report or graph - * - * @var array - */ - var $params = array(); - - /** - * The lables for calculated measures - * - * @var array - */ - var $labels = array(); - - /** - * Page results - * - * @var boolean - */ - var $page_results = false; - - /** - * Data Access Object - * - * @var object - */ - var $db; - - var $_default_offset = 0; - - var $pagination; - - var $page; - - var $limit; - - var $order; - - var $table; - - var $select = array(); - - var $time_period_constraint_format = 'timestamp'; - - var $column; - - var $is_calculated = false; - - var $is_aggregate; - - var $data_type; - - var $name; - - var $supported_data_types = array('percentage', 'decimal', 'integer', 'url', 'yyyymmdd', 'timestamp', 'string', 'currency'); - - function __construct($params = array()) { - - if (!empty($params)) { - $this->params = $params; - } - - //$this->db = owa_coreAPI::dbSingleton(); - - //$this->pagination = new owa_pagination; - - return parent::__construct(); - } - - /** - * Set the labels of the measures - * - */ - function setLabels($array) { - - $this->labels = $array; - return; - } - - /** - * Sets an individual label - * return the key so that it can be nested - * @return $key string - */ - function addLabel($key, $label) { - - $this->labels[$key] = $label; - return $key; - } - - function getLabel($key = '') { - - if (!$key) { - $key = $this->getName(); - } - - return $this->labels[$key]; - } - - /** - * Sets an individual label - * return the key so that it can be nested - * @return $key string - */ - function setLabel($label) { - - $this->labels[$this->getName()] = $label; - - } - - /** - * Retrieve the labels of the measures - * - */ - function getLabels() { - - return $this->labels; - - } - /* - - function getPagination() { - - $count = $this->calculatePaginationCount(); - $this->pagination->total_count = $count; - return $this->pagination->getPagination(); - - } - - */ - function zeroFill(&$array) { - - // PHP 5 only function used here - if (function_exists("array_walk_recursive")) { - array_walk_recursive($array, array($this, 'addzero')); - } else { - owa_lib::array_walk_recursive($array, array(get_class($this).'Metric', 'addzero')); - } - - return $array; - - } - - function addzero(&$v, $k) { - - if (empty($v)) { - - $v = 0; - - } - - return; - } - /* - - function getPeriod() { - - return $this->params['period']; - } - - function getOrder() { - - if (array_key_exists('order', $this->params)) { - return $this->params['order']; - } - } - - function getLimit() { - - return $this->limit; - - } - - */ - function setEntity($name) { - - $this->entity = owa_coreAPI::entityFactory($name); - } - - function getTableName() { - - return $this->entity->getTableName(); - } - - function getTableAlias() { - - return $this->entity->getTableAlias(); - } - - function setSelect($column, $as = '') { - - if (!$as) { - - $as = $this->getName(); - } - - $this->select = array($column, $as); - } - - function getSelect() { - - if ( $this->select) { - // old style metrics populate this explicitly. - return $this->select; - } else { - $db = owa_coreAPI::dbSingleton(); - switch ( $this->type ) { - - case 'count': - - $statement = $db->count( $this->getColumn() ); - break; - - case 'distinct_count': - $statement = $db->count( $db->distinct( $this->getColumn() ) ); - break; - - case 'sum': - $statement = $db->sum( $this->getColumn() ); - break; - } - - return array( $statement, $this->getName() ); - } - - } - - function getSelectWithNoAlias() { - - if ( $this->select ) { - return $this->select[0]; - } else { - $select = $this->getSelect(); - return $select[0]; - } - } - - function setName($name) { - - $this->name = $name; - } - - function getName() { - - return $this->name; - } - - function getFormat() { - - if (array_key_exists('result_format', $this->params)) { - return $this->params['result_format']; - } - } - - /** - * Sets a metric's column - */ - function setColumn($col_name, $name = '') { - - if (!$name) { - $name = $this->getName(); - } - $this->column = $this->entity->getTableAlias().'.'.$col_name; - $this->all_columns[$name] = $this->column; - - } - - /** - * Gets a metric's column name - */ - function getColumn() { - - return $this->column; - } - - function getEntityName() { - return $this->entity->getName(); - } - - function isCalculated() { - return $this->is_calculated; - } - - function setDataType($string) { - - if (in_array($string, $this->supported_data_types)) { - $this->data_type = $string; - } - - } - - function getDataType() { - return $this->data_type; - } - - function setAggregate() { - - $this->is_aggregate = true; - } - - function isAggregate() { - - return $this->is_aggregate; - } - - function setMetricType( $type ) { - $this->type = $type; - - if ( $type === 'calculated' ) { - $this->is_calculated = true; - } - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ +class owa_metric extends owa_base { + + /** + * Current Time + * + * @var array + */ + var $time_now = array(); + + /** + * Data + * + * @var array + */ + var $data; + + /** + * The params of the caller, either a report or graph + * + * @var array + */ + var $params = array(); + + /** + * The lables for calculated measures + * + * @var array + */ + var $labels = array(); + + /** + * Page results + * + * @var boolean + */ + var $page_results = false; + + /** + * Data Access Object + * + * @var object + */ + var $db; + + var $_default_offset = 0; + + var $pagination; + + var $page; + + var $limit; + + var $order; + + var $table; + + var $select = array(); + + var $time_period_constraint_format = 'timestamp'; + + var $column; + + var $is_calculated = false; + + var $is_aggregate; + + var $data_type; + + var $name; + + var $supported_data_types = array('percentage', 'decimal', 'integer', 'url', 'yyyymmdd', 'timestamp', 'string', 'currency'); + + function __construct($params = array()) { + + if (!empty($params)) { + $this->params = $params; + } + + //$this->db = owa_coreAPI::dbSingleton(); + + //$this->pagination = new owa_pagination; + + return parent::__construct(); + } + + /** + * Set the labels of the measures + * + */ + function setLabels($array) { + + $this->labels = $array; + return; + } + + /** + * Sets an individual label + * return the key so that it can be nested + * @return $key string + */ + function addLabel($key, $label) { + + $this->labels[$key] = $label; + return $key; + } + + function getLabel($key = '') { + + if (!$key) { + $key = $this->getName(); + } + + return $this->labels[$key]; + } + + /** + * Sets an individual label + * return the key so that it can be nested + * @return $key string + */ + function setLabel($label) { + + $this->labels[$this->getName()] = $label; + + } + + /** + * Retrieve the labels of the measures + * + */ + function getLabels() { + + return $this->labels; + + } + /* + + function getPagination() { + + $count = $this->calculatePaginationCount(); + $this->pagination->total_count = $count; + return $this->pagination->getPagination(); + + } + + */ + function zeroFill(&$array) { + + // PHP 5 only function used here + if (function_exists("array_walk_recursive")) { + array_walk_recursive($array, array($this, 'addzero')); + } else { + owa_lib::array_walk_recursive($array, array(get_class($this).'Metric', 'addzero')); + } + + return $array; + + } + + function addzero(&$v, $k) { + + if (empty($v)) { + + $v = 0; + + } + + return; + } + /* + + function getPeriod() { + + return $this->params['period']; + } + + function getOrder() { + + if (array_key_exists('order', $this->params)) { + return $this->params['order']; + } + } + + function getLimit() { + + return $this->limit; + + } + + */ + function setEntity($name) { + + $this->entity = owa_coreAPI::entityFactory($name); + } + + function getTableName() { + + return $this->entity->getTableName(); + } + + function getTableAlias() { + + return $this->entity->getTableAlias(); + } + + function setSelect($column, $as = '') { + + if (!$as) { + + $as = $this->getName(); + } + + $this->select = array($column, $as); + } + + function getSelect() { + + if ( $this->select) { + // old style metrics populate this explicitly. + return $this->select; + } else { + $db = owa_coreAPI::dbSingleton(); + switch ( $this->type ) { + + case 'count': + + $statement = $db->count( $this->getColumn() ); + break; + + case 'distinct_count': + $statement = $db->count( $db->distinct( $this->getColumn() ) ); + break; + + case 'sum': + $statement = $db->sum( $this->getColumn() ); + break; + } + + return array( $statement, $this->getName() ); + } + + } + + function getSelectWithNoAlias() { + + if ( $this->select ) { + return $this->select[0]; + } else { + $select = $this->getSelect(); + return $select[0]; + } + } + + function setName($name) { + + $this->name = $name; + } + + function getName() { + + return $this->name; + } + + function getFormat() { + + if (array_key_exists('result_format', $this->params)) { + return $this->params['result_format']; + } + } + + /** + * Sets a metric's column + */ + function setColumn($col_name, $name = '') { + + if (!$name) { + $name = $this->getName(); + } + $this->column = $this->entity->getTableAlias().'.'.$col_name; + $this->all_columns[$name] = $this->column; + + } + + /** + * Gets a metric's column name + */ + function getColumn() { + + return $this->column; + } + + function getEntityName() { + return $this->entity->getName(); + } + + function isCalculated() { + return $this->is_calculated; + } + + function setDataType($string) { + + if (in_array($string, $this->supported_data_types)) { + $this->data_type = $string; + } + + } + + function getDataType() { + return $this->data_type; + } + + function setAggregate() { + + $this->is_aggregate = true; + } + + function isAggregate() { + + return $this->is_aggregate; + } + + function setMetricType( $type ) { + $this->type = $type; + + if ( $type === 'calculated' ) { + $this->is_calculated = true; + } + } +} + ?> \ No newline at end of file diff --git a/owa_module.php b/owa_module.php index edfd91f44..8ca5535ba 100644 --- a/owa_module.php +++ b/owa_module.php @@ -1,1194 +1,1194 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -abstract class owa_module extends owa_base { - - /** - * Name of module - * - * @var string - */ - var $name; - - /** - * Description of Module - * - * @var string - */ - var $description; - - /** - * Version of Module - * - * @var string - */ - var $version; - - /** - * Schema Version of Module - * - * @var string - */ - //var $schema_version = 1; - - /** - * Name of author of module - * - * @var string - */ - var $author; - - /** - * URL for author of module - * - * @var unknown_type - */ - var $author_url; - - /** - * Wiki Page title. Used to generate link to OWA wiki for this module. - * - * Must be unique or else it will could clobber another wiki page. - * - * @var string - */ - var $wiki_title; - - /** - * name used in display situations - * - * @var unknown_type - */ - var $display_name; - - /** - * Array of event names that this module has handlers for - * - * @var array - */ - var $subscribed_events; - - /** - * Array of link information for admin panels that this module implements. - * - * @var array - */ - var $admin_panels; - - /** - * Array of navigation links that this module implements - * - * @var unknown_type - */ - var $nav_links; - - /** - * Array of metric names that this module implements - * - * @var unknown_type - */ - var $metrics; - - /** - * Array of graphs that are implemented by this module - * - * @var array - */ - var $graphs; - - /** - * The Module Group that the module belongs to. - * - * This is used often to group a module's features or functions together in the UI - * - * @var string - */ - var $group; - - /** - * Array of Entities that are implmented by the module - * - * @var array - */ - var $entities = array(); - - /** - * Required Schema Version - * - * @var array - */ - var $required_schema_version; - - /** - * Available Updates - * - * @var array - */ - var $updates = array(); - - /** - * Event Processors Map - * - * @var array - */ - var $event_processors = array(); - - /** - * Dimensions - * - * @var array - */ - var $dimensions = array(); - - /** - * Dimensions - * - * @var array - */ - var $denormalizedDimensions = array(); - - /** - * - * @var array - */ - var $formatters = array(); - - /** - * cli_commands - * - * @var array - */ - var $cli_commands = array(); - - /** - * API Methods - * - * @var array - */ - var $api_methods = array(); - - /** - * Background Jobs - * - * @var array - */ - var $background_jobs = array(); - - /** - * Controllers - * - * @var array - */ - var $actionControllers = array(); - - /** - * Update from CLI Required flag - * - * Used by controllers to see if an update error was becuase it needs - * to be applied from the command line instead of via the browser. - * - * @var boolean - */ - var $update_from_cli_required; - - /** - * Constructor - * - * - */ - function __construct() { - - parent::__construct(); - - /** - * Register Filters - */ - //$this->registerFilters(); - - /** - * Register Metrics - */ - $this->registerMetrics(); - - /** - * Register Dimensions - */ - $this->registerDimensions(); - - /** - * Register CLI Commands - */ - $this->registerCliCommands(); - - /** - * Register API Methods - */ - $this->registerApiMethods(); - - /** - * Register Background Jobs - */ - $this->registerBackgroundJobs(); - - /** - * Register Build Packages - */ - $this->registerBuildPackages(); - - $this->_registerEventHandlers(); - $this->_registerEventProcessors(); - $this->_registerEntities(); - - } - - /** - * Method for registering event processors - * - */ - function _registerEventProcessors() { - - return false; - } - - /** - * Returns array of admin Links for this module to be used in navigation - * - * @access public - * @return array - */ - function getAdminPanels() { - - return $this->admin_panels; - } - - /** - * Returns array of report links for this module that will be - * used in report navigation - * - * @access public - * @return array - */ - function getNavigationLinks() { - - return $this->nav_links; - } - - /** - * Abstract method for registering event handlers - * - * Must be defined by a concrete module class for any event handlers to be registered - * - * @access public - * @return array - */ - function _registerEventHandlers() { - - return; - } - - /** - * Attaches an event handler to the event queue - * - * @param array $event_name - * @param string $handler_name - * @return boolean - */ - function registerEventHandler($event_name, $handler_name, $method = 'notify', $dir = 'handlers') { - - if (!is_object($handler_name)) { - - //$handler = &owa_lib::factory($handler_dir,'owa_', $handler_name); - $handler_name = owa_coreAPI::moduleGenericFactory($this->name, $dir, $handler_name, $class_suffix = null, $params = '', $class_ns = 'owa_'); - } - - $eq = owa_coreAPI::getEventDispatch(); - $eq->attach($event_name, array($handler_name, $method)); - } - - /** - * Hooks a function to a filter - * - * @param array $event_name - * @param string $handler_name - * @return boolean - */ - function registerFilter($filter_name, $handler_name, $method = '', $priority = 10, $dir = 'filters') { - - // if it's an object - if ( is_object( $handler_name ) ) { - - owa_coreAPI::registerFilter($filter_name, array($handler_name, $method), $priority); - - // if it's a static method name - } elseif ( strpos( $handler_name, '::') ) { - - owa_coreAPI::registerFilter($filter_name, $handler_name, $priority); - - // else try to create the class object - } else { - // create object - if ( ! class_exists( $handler_name ) ) { - - //$handler = &owa_lib::factory($handler_dir,'owa_', $handler_name); - $class = owa_coreAPI::moduleGenericFactory($this->name, $dir, $handler_name, $class_suffix = null, $params = '', $class_ns = 'owa_'); - } - - // register - owa_coreAPI::registerFilter($filter_name, array($class, $method), $priority); - } - } - - /** - * Attaches an event handler to the event queue - * - * @param array $event_name - * @param string $handler_name - * @return boolean - * @depricated - */ - function _addHandler($event_name, $handler_name) { - - return $this->registerEventHandler($event_name, $handler_name); - - } - - /** - * Abstract method for registering administration/settings page - * - * @access public - * @return array - */ - function registerAdminPanels() { - - return; - } - - /** - * Registers an admin panel with this module - * - */ - function registerSettingsPanel($panel) { - - $this->admin_panels[] = $panel; - - return true; - } - - /** - * Registers an admin panel with this module - * @depricated - */ - function addAdminPanel($panel) { - - return $this->registerSettingsPanel($panel); - } - - /** - * Registers Group Link with a particular View - * @DEPRICATED - use addNavigationSubGroup and addNavigationLinkInSubGroup - */ - function addNavigationLink($group, $subgroup = '', $ref, $anchortext, $order = 0, $priviledge = 'view_reports') { - - if (!empty($subgroup)): - $this->addNavigationLinkInSubGroup($subgroup,$ref, $anchortext, $order = 0, $priviledge ,$group); - else: - $this->addNavigationSubGroup($anchortext,$ref, $anchortext, $order = 0, $priviledge ,$group); - endif; - - return; - } - - /** - * Adds a new Subgroup in the navigation - * - * @param string $subgroupName - * @param string $ref - * @param string $anchortext - * @param integer $order - * @param string $priviledge - * @param string $groupName - */ - public function addNavigationSubGroup($subgroupName, $ref, $anchortext, $order = 0, $priviledge = 'view_reports', $groupName = 'Reports') { - $this->nav_links[$groupName][$subgroupName] = $this->getLinkStruct($ref, $anchortext, $order,$priviledge); - } - - /** - * Adds a new Link to an existing Subgroup in the navigation - * - * @param string $subgroupName - * @param string $ref - * @param string $anchortext - * @param integer $order - * @param string $priviledge - * @param string $groupName - */ - public function addNavigationLinkInSubGroup($subgroupName, $ref, $anchortext, $order = 0, $priviledge = 'view_reports', $groupName = 'Reports') { - $this->nav_links[$groupName][$subgroupName]['subgroup'][] = $this->getLinkStruct($ref, $anchortext, $order,$priviledge); - } - - /** - * Abstract method for registering a module's entities - * - * This method must be defined in concrete module classes in order for entities to be registered. - */ - function _registerEntities() { - - return false; - } - - function registerNavigation() { - - return false; - } - - - /** - * Registers an Entity - * - * Can take an array of entities or just a single entity as a string. - * Will add an enetiy to the module's entity array. Required for entity installation, etc. - * - * @param $entity_name array or string - */ - function registerEntity($entity_name) { - - if (is_array($entity_name)) { - $this->entities = array_merge($this->entities, $entity_name); - } else { - $this->entities[] = $entity_name; - } - } - - /** - * Registers Entity - * - * Depreicated see registerEntity - * - * @depricated - */ - function _addEntity($entity_name) { - - return $this->registerEntity($entity_name); - } - - - function getEntities() { - - return $this->entities; - } - - /** - * Installation method - * - * Creates database tables and sets schema version - * - */ - function install() { - - $this->e->notice('Starting installation of module: '.$this->name); - - $errors = ''; - - // Install schema - if (!empty($this->entities)) { - - foreach ($this->entities as $k => $v) { - - $entity = owa_coreAPI::entityFactory($this->name.'.'.$v); - //$this->e->debug("about to execute createtable"); - $status = $entity->createTable(); - - if ($status != true) { - $this->e->notice("Entity Installation Failed."); - $errors = true; - //return false; - } - - } - } - - // activate module and persist configuration changes - if ($errors != true) { - - // run post install hook - $ret = $this->postInstall(); - - if ($ret == true): - $this->e->notice("Post install proceadure was a success.");; - else: - $this->e->notice("Post install proceadure failed."); - endif; - - // save schema version to configuration - $this->c->persistSetting($this->name, 'schema_version', $this->getRequiredSchemaVersion()); - //activate the module and save the configuration - $this->activate(); - $this->e->notice("Installation complete."); - return true; - - } else { - $this->e->notice("Installation failed."); - return false; - } - - } - - /** - * Post installation hook - * - */ - function postInstall() { - - return true; - } - - function isCliUpdateModeRequired() { - - return $this->update_from_cli_required; - } - - /** - * Checks for and applies schema upgrades for the module - * - */ - function update() { - - // list files in a directory - $files = owa_lib::listDir(OWA_DIR.'modules'.'/'.$this->name.'/'.'updates', false); - //print_r($files); - - $current_schema_version = $this->c->get($this->name, 'schema_version'); - - // extract sequence - foreach ($files as $k => $v) { - // the use of %d casts the sequence number as an int which is critical for maintaining the - // order of the keys in the array that we are going ot create that holds the update objs - //$n = sscanf($v['name'], '%d_%s', $seq, $classname); - $seq = substr($v['name'], 0, -4); - - settype($seq, "integer"); - - if ($seq > $current_schema_version) { - - if ($seq <= $this->required_schema_version) { - $this->updates[$seq] = owa_coreAPI::updateFactory($this->name, substr($v['name'], 0, -4)); - // if the cli update mode is required and we are not running via cli then return an error. - owa_coreAPI::debug('cli update mode required: '.$this->updates[$seq]->isCliModeRequired()); - if ($this->updates[$seq]->isCliModeRequired() === true && !defined('OWA_CLI')) { - //set flag in module - $this->update_from_cli_required = true; - owa_coreAPI::notice("Aborting update $seq. This update must be applied using the command line interface."); - return false; - } - // set schema version from sequence number in file name. This ensures that only one update - // class can ever be in use for a particular schema version - $this->updates[$seq]->schema_version = $seq; - } - } - - } - - // sort the array - ksort($this->updates, SORT_NUMERIC); - - //print_r(array_keys($this->updates)); - - foreach ($this->updates as $k => $obj) { - - $this->e->notice(sprintf("Applying Update %d (%s)", $k, get_class($obj))); - - $ret = $obj->apply(); - - if ($ret == true): - $this->e->notice("Update Suceeded"); - else: - $this->e->notice("Update Failed"); - return false; - endif; - } - - return true; - } - - /** - * Deactivates and removes schema for the module - * - */ - function uninstall() { - - return; - } - - /** - * Places the Module into the active module list in the global configuration - * - */ - function activate() { - - //if ($this->name != 'base'): - - $this->c->persistSetting($this->name, 'is_active', true); - $this->c->save(); - $this->e->notice("Module $this->name activated"); - - //endif; - - return; - } - - /** - * Deactivates the module by removing it from - * the active module list in the global configuration - * - */ - function deactivate() { - - if ($this->name != 'base'): - - $this->c->persistSetting($this->name, 'is_active', false); - $this->c->save(); - - endif; - - return; - } - - /** - * Checks to se if the schema is up to date - * - */ - function isSchemaCurrent() { - - $current_schema = $this->getSchemaVersion(); - $required_schema = $this->getRequiredSchemaVersion(); - - owa_coreAPI::debug("$this->name Schema version is $current_schema"); - owa_coreAPI::debug("$this->name Required Schema version is $required_schema"); - - if ($current_schema >= $required_schema) { - return true; - } else { - return false; - } - } - - function getSchemaVersion() { - - $current_schema = owa_coreAPI::getSetting($this->name, 'schema_version'); - - if (empty($current_schema)) { - $current_schema = 1; - - // if this is the base module then we need to let filters know to install the base schema - if ($this->name === 'base') { - // $s = owa_coreAPI::serviceSingleton(); - // $s->setInstallRequired(); - } - } - - return $current_schema; - } - - function getRequiredSchemaVersion() { - - return $this->required_schema_version; - } - - /** - * Registers updates - * - */ - function _registerUpdates() { - - return; - - } - - /** - * Adds an update class into the update array. - * This should be used to within the _registerUpdates method or else - * it will not get called. - * - */ - function _addUpdate($sequence, $class) { - - $this->updates[$sequence] = $class; - - return true; - } - - /** - * Adds an event processor class to the processor array. This is used to determin - * which class to use to process a particular event - */ - function addEventProcessor($event_type, $processor) { - $this->event_processors[$event_type] = $processor; - return; - } - - function registerMetric($metric_name, $classes, $params = array(), $label = '', $description = '', $group = '') { - - if ( ! $label ) { - $label = $metric_name; - } - - if ( ! $description ) { - $description = 'No description available.'; - } - - if ( ! is_array( $classes ) ) { - - $classes = array($classes); - } - - foreach ($classes as $class_name) { - - $map = array('name' => $metric_name, 'class' => $class_name, 'params' => $params, 'label' => $label, 'description' => $description, 'group' => $group); - $this->metrics[$metric_name][] = $map; - } - } - - /** - * Registers a metric definition which is used by the - * resultSetExplorer and getResultSet API methods - * - * This method dynamically creates an owa_metric class and - * properly configures it based on the properties passed in. - * - * Map properties include: - * - * 'name' => '', // the name of the metric as called via the API - * 'label' => '', // the label that will be displayed in result sets - * 'description' => '', // the descript displayed in the GUI - * 'group' => 'unknown', // the group that this metric will belong to in the UI - * 'entity' => '', // the entity to use when calculating this metric - * // you must register the same metric for each entity that - * // it can be calculated on. - * 'metric_type' => '', // 'count', 'distinct_count', 'sum', or 'calculated' - * 'data_type' => '', // 'integrer', 'currency', 'average' - * 'column' => '', // the column of the entity to use when calculating - * 'child_metrics' => array(), // if it's a clculated metric, the child metrics used in the formula. - * 'formula' => '' // if it's a calculated metric, the formula to use (e.g. pageViews / visits). - * - * - */ - function registerMetricDefinition( $params ) { - - $map = array( - 'name' => '', - 'label' => '', - 'description' => '', - 'group' => 'unknown', - 'entity' => '', - 'metric_type' => '', - 'data_type' => '', - 'column' => '', - 'child_metrics' => array(), - 'formula' => '' - ); - - $map = array_intersect_key( array_merge( $map, $params ), $map ); - - if ( ! isset( $map['name'] ) ) { - // throw exception - } - - if ( ! isset( $map['label'] ) ) { - $map['label'] = $map['name']; - } - - if ( ! isset( $map['entity'] ) ) { - // throw exception - } - - if ( ! isset( $map['metric_type'] ) ) { - // throw exception - } - - if ( ! isset( $map['data_type'] ) ) { - // throw exception - } - - if ( isset( $map['metric_type'] ) - && $map['metric_type'] != 'calculated' - && ! isset( $map['column'] ) ) - { - - // throw exception - - } - - if ( isset( $map['metric_type'] ) - && $map['metric_type'] === 'calculated' - && ! isset( $map['child_metrics'] ) ) - { - - // throw exception - - } - - if ( isset( $map['metric_type'] ) - && $map['metric_type'] === 'calculated' - && ! isset( $map['formula'] ) ) - { - - // throw exception - - } - - $definition = array( - 'name' => $map['name'], - 'class' => 'base.configurableMetric', - 'params' => $map, - 'label' => $map['label'], - 'description' => $map['description'], - 'group' => $map['group'] - ); - //print_r($definition); - $this->metrics[ $map['name'] ][] = $definition; - - } - - /** - * Register a dimension - * - * registers a dimension for use by metrics in producing results sets. - * - * @param $dim_name string - * @param $entity_names string||array the names of entity housing the dimension. uses module.name format - * @param $column string the name of the column that represents the dimension - * @param $family string the name of the group or family that this dimension belongs to. optional. - * @param $description string a short description of this metric, used in various interfaces. - * @param $label string the lable of the dimension - * @param $foreign_key_name the name of the foreign key column that should - * be used to relate the metric entity to the dimension's entity. - * If one is not specfied, metrics will use any valid foreign key column they can find. - * Specifying this is important when the same column in a table is used by - * two different dimensions but the meaning of the column differs based on the value of the foreign key. - * a good example is the page_title column in the documents table. It is used by three dimensions: - * pageTitle, entryPageTitle, and existPageTitle. - * @param $denormalized boolean flag marks the dimension as being denormalized into a fact table - * as opposed to being housed in a related table. - */ - function registerDimension( - $dim_name, $entity_names, $column, $label = '', $family, - $description = '', $foreign_key_name = '', - $denormalized = false, $data_type = 'string') { - - if ( ! is_array( $entity_names ) ) { - $entity_names = array($entity_names); - } - - foreach ($entity_names as $entity) { - - $dim = array( - 'family' => $family, - 'name' => $dim_name, - 'entity' => $entity, - 'column' => $column, - 'label' => $label, - 'description' => $description, - 'foreign_key_name' => $foreign_key_name, - 'data_type' => $data_type, - 'denormalized' => $denormalized - ); - - if ($denormalized) { - $this->denormalizedDimensions[$dim_name][$entity] = $dim; - } else { - $this->dimensions[$dim_name] = $dim; - } - } - } - - function registerActions() { - - return false; - } - - - /** - * Registers an Action Controller - * - * @param $action_name string the name of the action used as the value in the 'do' url param - * @param $class_name string the name of the controller class - * @param $file string the path to the file housing the class - * - */ - protected function registerAction( $action_name, $class_name, $file = '' ) { - - $s = owa_coreAPI::serviceSingleton(); - $s->setMapValue( 'actions', $action_name, array( 'class_name' => $class_name, 'file' => $file ) ); - - } - - function registerCliCommand($command, $class) { - - $this->cli_commands[$command] = $class; - } - - function registerFormatter($type, $formatter) { - - $this->formatters[$type] = $formatter; - } - - function registerApiMethod($api_method_name, $user_function, $argument_names, $file = '', $required_capability = '') { - - $map = array('callback' => $user_function, 'args' => $argument_names, 'file' => $file); - - if ($required_capability) { - $map['required_capability'] = $required_capability; - } - - $this->api_methods[$api_method_name] = $map; - } - - function registerImplementation($type, $name, $class_name, $file) { - - $s = owa_coreAPI::serviceSingleton(); - $class_info = array($class_name, $file); - $s->setMapValue($type, $name, $class_info); - } - - function registerBackgroundJob($name, $command, $cron_tab, $max_processes = 1) { - - $job = array('name' => $name, - 'cron_tab' => $cron_tab, - 'command' => $command, - 'max_processes' => $max_processes); - - $s = owa_coreAPI::serviceSingleton(); - $s->setMapValue('background_jobs', $name, $job); - } - - /** - * Register Environmental Tracking Properties - * - * These are tracking properties that are derived from the Server environment - * and should be added to all tracking tracking events as they are recieved. - * - * - * @var $type string the type of tracking property environmental|regular|derived - * - * environmental = properties that are only dependant on the PHP SERVER environment. - * regular = properties that are set by clients - * derived = properties that are derived from or dependant on other properties - * - * @var $properties array an associative array of tracking properties - * - * Example: - * - * 'REMOTE_HOST' => array( - * 'default_value' => array( 'owa_trackingEventHelpers::remoteHostDefault' ), - * 'required' => true, - * 'data_type' => 'string', - * 'filter' => true - * ) - * - * - * The key of the array is the name the property - */ - - function registerTrackingProperties( $type, $properties = array() ) { - - switch( strtolower( $type ) ) { - - case 'environmental': - $map_key = 'tracking_properties_environmental'; - break; - - case 'regular': - $map_key = 'tracking_properties_regular'; - break; - - case 'derived': - $map_key = 'tracking_properties_derived'; - break; - - default: - $map_key = ''; - } - - if ( is_array( $properties ) && $map_key ) { - - $s = owa_coreAPI::serviceSingleton(); - - foreach ( $properties as $k => $property ) { - - $s->setMapValue( $map_key, $k, $property); - } - } - } - - /** - * Abstract method for registering individual API methods - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerApiMethods() { - - return false; - } - - /** - * Abstract method for registering individual CLI commands - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerCliCommands() { - - return false; - } - - /** - * Abstract method for registering individual Metrics - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerMetrics() { - - return false; - } - - /** - * Abstract method for registering individual CLI commands - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerDimensions() { - - return false; - } - - /** - * Abstract method for registering individual Filter Methods - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerFilters() { - - return false; - } - - /** - * Abstract method for registering individual Filter Methods - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerBackgroundJobs() { - - return false; - } - - /** - * Abstract method for registering package files to build - * - * This method is called by a module's constructor - * and should be redefined in a concrete module class. - */ - function registerBuildPackages() { - - return false; - } - - /** - * Registers a new package of files to be built by - * the 'build' CLI command. - * - * $package array the package array takes the form of - * - * 'name' => 'mypackage' - * 'output_dir' => '/path/to/output' - * 'files' => array('foo' => array('path' => '/path/to/file/file.js', - * 'compression' => 'minify')) - */ - protected function registerBuildPackage( $package ) { - - if (! isset( $package['name'] ) ) { - - throw exception('Build Package does not have a name.'); - } - - if (! isset( $package['output_dir'] ) ) { - - throw exception('Build Package does not have an output directory.'); - } else { - //check for trailing slash - $check = substr($package['output_dir'], -1, 1); - if ($check != '/') { - $package['output_dir'] = $package['output_dir'].'/'; - } - } - - if (! isset( $package['files'] ) ) { - - throw exception('Build Package does not any files.'); - } - - // filter the pcakge in case other modules want to change something. - $eq = owa_coreAPI::getEventDispatch(); - $package = $eq->filter( 'register_build_package', $package ); - - $s = owa_coreAPI::serviceSingleton(); - $s->setMapValue('build_packages', $package['name'], $package); - } - - - /** - * Retuns internal struct array used for saving link infos - * @param string $ref - * @param string $anchortext - * @param integer $order - * @param string $priviledge - * @return array - */ - private function getLinkStruct($ref,$anchortext,$order,$priviledge) { - return array('ref' => $ref, - 'anchortext' => $anchortext, - 'order' => $order, - 'priviledge' => $priviledge); - } - - protected function registerEventQueue( $name, $map ) { - - $map['queue_name'] = $name; - $s = owa_coreAPI::serviceSingleton(); - $s->setMapValue( 'event_queues', $name, $map ); - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +abstract class owa_module extends owa_base { + + /** + * Name of module + * + * @var string + */ + var $name; + + /** + * Description of Module + * + * @var string + */ + var $description; + + /** + * Version of Module + * + * @var string + */ + var $version; + + /** + * Schema Version of Module + * + * @var string + */ + //var $schema_version = 1; + + /** + * Name of author of module + * + * @var string + */ + var $author; + + /** + * URL for author of module + * + * @var unknown_type + */ + var $author_url; + + /** + * Wiki Page title. Used to generate link to OWA wiki for this module. + * + * Must be unique or else it will could clobber another wiki page. + * + * @var string + */ + var $wiki_title; + + /** + * name used in display situations + * + * @var unknown_type + */ + var $display_name; + + /** + * Array of event names that this module has handlers for + * + * @var array + */ + var $subscribed_events; + + /** + * Array of link information for admin panels that this module implements. + * + * @var array + */ + var $admin_panels; + + /** + * Array of navigation links that this module implements + * + * @var unknown_type + */ + var $nav_links; + + /** + * Array of metric names that this module implements + * + * @var unknown_type + */ + var $metrics; + + /** + * Array of graphs that are implemented by this module + * + * @var array + */ + var $graphs; + + /** + * The Module Group that the module belongs to. + * + * This is used often to group a module's features or functions together in the UI + * + * @var string + */ + var $group; + + /** + * Array of Entities that are implmented by the module + * + * @var array + */ + var $entities = array(); + + /** + * Required Schema Version + * + * @var array + */ + var $required_schema_version; + + /** + * Available Updates + * + * @var array + */ + var $updates = array(); + + /** + * Event Processors Map + * + * @var array + */ + var $event_processors = array(); + + /** + * Dimensions + * + * @var array + */ + var $dimensions = array(); + + /** + * Dimensions + * + * @var array + */ + var $denormalizedDimensions = array(); + + /** + * + * @var array + */ + var $formatters = array(); + + /** + * cli_commands + * + * @var array + */ + var $cli_commands = array(); + + /** + * API Methods + * + * @var array + */ + var $api_methods = array(); + + /** + * Background Jobs + * + * @var array + */ + var $background_jobs = array(); + + /** + * Controllers + * + * @var array + */ + var $actionControllers = array(); + + /** + * Update from CLI Required flag + * + * Used by controllers to see if an update error was becuase it needs + * to be applied from the command line instead of via the browser. + * + * @var boolean + */ + var $update_from_cli_required; + + /** + * Constructor + * + * + */ + function __construct() { + + parent::__construct(); + + /** + * Register Filters + */ + //$this->registerFilters(); + + /** + * Register Metrics + */ + $this->registerMetrics(); + + /** + * Register Dimensions + */ + $this->registerDimensions(); + + /** + * Register CLI Commands + */ + $this->registerCliCommands(); + + /** + * Register API Methods + */ + $this->registerApiMethods(); + + /** + * Register Background Jobs + */ + $this->registerBackgroundJobs(); + + /** + * Register Build Packages + */ + $this->registerBuildPackages(); + + $this->_registerEventHandlers(); + $this->_registerEventProcessors(); + $this->_registerEntities(); + + } + + /** + * Method for registering event processors + * + */ + function _registerEventProcessors() { + + return false; + } + + /** + * Returns array of admin Links for this module to be used in navigation + * + * @access public + * @return array + */ + function getAdminPanels() { + + return $this->admin_panels; + } + + /** + * Returns array of report links for this module that will be + * used in report navigation + * + * @access public + * @return array + */ + function getNavigationLinks() { + + return $this->nav_links; + } + + /** + * Abstract method for registering event handlers + * + * Must be defined by a concrete module class for any event handlers to be registered + * + * @access public + * @return array + */ + function _registerEventHandlers() { + + return; + } + + /** + * Attaches an event handler to the event queue + * + * @param array $event_name + * @param string $handler_name + * @return boolean + */ + function registerEventHandler($event_name, $handler_name, $method = 'notify', $dir = 'handlers') { + + if (!is_object($handler_name)) { + + //$handler = &owa_lib::factory($handler_dir,'owa_', $handler_name); + $handler_name = owa_coreAPI::moduleGenericFactory($this->name, $dir, $handler_name, $class_suffix = null, $params = '', $class_ns = 'owa_'); + } + + $eq = owa_coreAPI::getEventDispatch(); + $eq->attach($event_name, array($handler_name, $method)); + } + + /** + * Hooks a function to a filter + * + * @param array $event_name + * @param string $handler_name + * @return boolean + */ + function registerFilter($filter_name, $handler_name, $method = '', $priority = 10, $dir = 'filters') { + + // if it's an object + if ( is_object( $handler_name ) ) { + + owa_coreAPI::registerFilter($filter_name, array($handler_name, $method), $priority); + + // if it's a static method name + } elseif ( strpos( $handler_name, '::') ) { + + owa_coreAPI::registerFilter($filter_name, $handler_name, $priority); + + // else try to create the class object + } else { + // create object + if ( ! class_exists( $handler_name ) ) { + + //$handler = &owa_lib::factory($handler_dir,'owa_', $handler_name); + $class = owa_coreAPI::moduleGenericFactory($this->name, $dir, $handler_name, $class_suffix = null, $params = '', $class_ns = 'owa_'); + } + + // register + owa_coreAPI::registerFilter($filter_name, array($class, $method), $priority); + } + } + + /** + * Attaches an event handler to the event queue + * + * @param array $event_name + * @param string $handler_name + * @return boolean + * @depricated + */ + function _addHandler($event_name, $handler_name) { + + return $this->registerEventHandler($event_name, $handler_name); + + } + + /** + * Abstract method for registering administration/settings page + * + * @access public + * @return array + */ + function registerAdminPanels() { + + return; + } + + /** + * Registers an admin panel with this module + * + */ + function registerSettingsPanel($panel) { + + $this->admin_panels[] = $panel; + + return true; + } + + /** + * Registers an admin panel with this module + * @depricated + */ + function addAdminPanel($panel) { + + return $this->registerSettingsPanel($panel); + } + + /** + * Registers Group Link with a particular View + * @DEPRICATED - use addNavigationSubGroup and addNavigationLinkInSubGroup + */ + function addNavigationLink($group, $subgroup = '', $ref, $anchortext, $order = 0, $priviledge = 'view_reports') { + + if (!empty($subgroup)): + $this->addNavigationLinkInSubGroup($subgroup,$ref, $anchortext, $order = 0, $priviledge ,$group); + else: + $this->addNavigationSubGroup($anchortext,$ref, $anchortext, $order = 0, $priviledge ,$group); + endif; + + return; + } + + /** + * Adds a new Subgroup in the navigation + * + * @param string $subgroupName + * @param string $ref + * @param string $anchortext + * @param integer $order + * @param string $priviledge + * @param string $groupName + */ + public function addNavigationSubGroup($subgroupName, $ref, $anchortext, $order = 0, $priviledge = 'view_reports', $groupName = 'Reports') { + $this->nav_links[$groupName][$subgroupName] = $this->getLinkStruct($ref, $anchortext, $order,$priviledge); + } + + /** + * Adds a new Link to an existing Subgroup in the navigation + * + * @param string $subgroupName + * @param string $ref + * @param string $anchortext + * @param integer $order + * @param string $priviledge + * @param string $groupName + */ + public function addNavigationLinkInSubGroup($subgroupName, $ref, $anchortext, $order = 0, $priviledge = 'view_reports', $groupName = 'Reports') { + $this->nav_links[$groupName][$subgroupName]['subgroup'][] = $this->getLinkStruct($ref, $anchortext, $order,$priviledge); + } + + /** + * Abstract method for registering a module's entities + * + * This method must be defined in concrete module classes in order for entities to be registered. + */ + function _registerEntities() { + + return false; + } + + function registerNavigation() { + + return false; + } + + + /** + * Registers an Entity + * + * Can take an array of entities or just a single entity as a string. + * Will add an enetiy to the module's entity array. Required for entity installation, etc. + * + * @param $entity_name array or string + */ + function registerEntity($entity_name) { + + if (is_array($entity_name)) { + $this->entities = array_merge($this->entities, $entity_name); + } else { + $this->entities[] = $entity_name; + } + } + + /** + * Registers Entity + * + * Depreicated see registerEntity + * + * @depricated + */ + function _addEntity($entity_name) { + + return $this->registerEntity($entity_name); + } + + + function getEntities() { + + return $this->entities; + } + + /** + * Installation method + * + * Creates database tables and sets schema version + * + */ + function install() { + + $this->e->notice('Starting installation of module: '.$this->name); + + $errors = ''; + + // Install schema + if (!empty($this->entities)) { + + foreach ($this->entities as $k => $v) { + + $entity = owa_coreAPI::entityFactory($this->name.'.'.$v); + //$this->e->debug("about to execute createtable"); + $status = $entity->createTable(); + + if ($status != true) { + $this->e->notice("Entity Installation Failed."); + $errors = true; + //return false; + } + + } + } + + // activate module and persist configuration changes + if ($errors != true) { + + // run post install hook + $ret = $this->postInstall(); + + if ($ret == true): + $this->e->notice("Post install proceadure was a success.");; + else: + $this->e->notice("Post install proceadure failed."); + endif; + + // save schema version to configuration + $this->c->persistSetting($this->name, 'schema_version', $this->getRequiredSchemaVersion()); + //activate the module and save the configuration + $this->activate(); + $this->e->notice("Installation complete."); + return true; + + } else { + $this->e->notice("Installation failed."); + return false; + } + + } + + /** + * Post installation hook + * + */ + function postInstall() { + + return true; + } + + function isCliUpdateModeRequired() { + + return $this->update_from_cli_required; + } + + /** + * Checks for and applies schema upgrades for the module + * + */ + function update() { + + // list files in a directory + $files = owa_lib::listDir(OWA_DIR.'modules'.'/'.$this->name.'/'.'updates', false); + //print_r($files); + + $current_schema_version = $this->c->get($this->name, 'schema_version'); + + // extract sequence + foreach ($files as $k => $v) { + // the use of %d casts the sequence number as an int which is critical for maintaining the + // order of the keys in the array that we are going ot create that holds the update objs + //$n = sscanf($v['name'], '%d_%s', $seq, $classname); + $seq = substr($v['name'], 0, -4); + + settype($seq, "integer"); + + if ($seq > $current_schema_version) { + + if ($seq <= $this->required_schema_version) { + $this->updates[$seq] = owa_coreAPI::updateFactory($this->name, substr($v['name'], 0, -4)); + // if the cli update mode is required and we are not running via cli then return an error. + owa_coreAPI::debug('cli update mode required: '.$this->updates[$seq]->isCliModeRequired()); + if ($this->updates[$seq]->isCliModeRequired() === true && !defined('OWA_CLI')) { + //set flag in module + $this->update_from_cli_required = true; + owa_coreAPI::notice("Aborting update $seq. This update must be applied using the command line interface."); + return false; + } + // set schema version from sequence number in file name. This ensures that only one update + // class can ever be in use for a particular schema version + $this->updates[$seq]->schema_version = $seq; + } + } + + } + + // sort the array + ksort($this->updates, SORT_NUMERIC); + + //print_r(array_keys($this->updates)); + + foreach ($this->updates as $k => $obj) { + + $this->e->notice(sprintf("Applying Update %d (%s)", $k, get_class($obj))); + + $ret = $obj->apply(); + + if ($ret == true): + $this->e->notice("Update Suceeded"); + else: + $this->e->notice("Update Failed"); + return false; + endif; + } + + return true; + } + + /** + * Deactivates and removes schema for the module + * + */ + function uninstall() { + + return; + } + + /** + * Places the Module into the active module list in the global configuration + * + */ + function activate() { + + //if ($this->name != 'base'): + + $this->c->persistSetting($this->name, 'is_active', true); + $this->c->save(); + $this->e->notice("Module $this->name activated"); + + //endif; + + return; + } + + /** + * Deactivates the module by removing it from + * the active module list in the global configuration + * + */ + function deactivate() { + + if ($this->name != 'base'): + + $this->c->persistSetting($this->name, 'is_active', false); + $this->c->save(); + + endif; + + return; + } + + /** + * Checks to se if the schema is up to date + * + */ + function isSchemaCurrent() { + + $current_schema = $this->getSchemaVersion(); + $required_schema = $this->getRequiredSchemaVersion(); + + owa_coreAPI::debug("$this->name Schema version is $current_schema"); + owa_coreAPI::debug("$this->name Required Schema version is $required_schema"); + + if ($current_schema >= $required_schema) { + return true; + } else { + return false; + } + } + + function getSchemaVersion() { + + $current_schema = owa_coreAPI::getSetting($this->name, 'schema_version'); + + if (empty($current_schema)) { + $current_schema = 1; + + // if this is the base module then we need to let filters know to install the base schema + if ($this->name === 'base') { + // $s = owa_coreAPI::serviceSingleton(); + // $s->setInstallRequired(); + } + } + + return $current_schema; + } + + function getRequiredSchemaVersion() { + + return $this->required_schema_version; + } + + /** + * Registers updates + * + */ + function _registerUpdates() { + + return; + + } + + /** + * Adds an update class into the update array. + * This should be used to within the _registerUpdates method or else + * it will not get called. + * + */ + function _addUpdate($sequence, $class) { + + $this->updates[$sequence] = $class; + + return true; + } + + /** + * Adds an event processor class to the processor array. This is used to determin + * which class to use to process a particular event + */ + function addEventProcessor($event_type, $processor) { + $this->event_processors[$event_type] = $processor; + return; + } + + function registerMetric($metric_name, $classes, $params = array(), $label = '', $description = '', $group = '') { + + if ( ! $label ) { + $label = $metric_name; + } + + if ( ! $description ) { + $description = 'No description available.'; + } + + if ( ! is_array( $classes ) ) { + + $classes = array($classes); + } + + foreach ($classes as $class_name) { + + $map = array('name' => $metric_name, 'class' => $class_name, 'params' => $params, 'label' => $label, 'description' => $description, 'group' => $group); + $this->metrics[$metric_name][] = $map; + } + } + + /** + * Registers a metric definition which is used by the + * resultSetExplorer and getResultSet API methods + * + * This method dynamically creates an owa_metric class and + * properly configures it based on the properties passed in. + * + * Map properties include: + * + * 'name' => '', // the name of the metric as called via the API + * 'label' => '', // the label that will be displayed in result sets + * 'description' => '', // the descript displayed in the GUI + * 'group' => 'unknown', // the group that this metric will belong to in the UI + * 'entity' => '', // the entity to use when calculating this metric + * // you must register the same metric for each entity that + * // it can be calculated on. + * 'metric_type' => '', // 'count', 'distinct_count', 'sum', or 'calculated' + * 'data_type' => '', // 'integrer', 'currency', 'average' + * 'column' => '', // the column of the entity to use when calculating + * 'child_metrics' => array(), // if it's a clculated metric, the child metrics used in the formula. + * 'formula' => '' // if it's a calculated metric, the formula to use (e.g. pageViews / visits). + * + * + */ + function registerMetricDefinition( $params ) { + + $map = array( + 'name' => '', + 'label' => '', + 'description' => '', + 'group' => 'unknown', + 'entity' => '', + 'metric_type' => '', + 'data_type' => '', + 'column' => '', + 'child_metrics' => array(), + 'formula' => '' + ); + + $map = array_intersect_key( array_merge( $map, $params ), $map ); + + if ( ! isset( $map['name'] ) ) { + // throw exception + } + + if ( ! isset( $map['label'] ) ) { + $map['label'] = $map['name']; + } + + if ( ! isset( $map['entity'] ) ) { + // throw exception + } + + if ( ! isset( $map['metric_type'] ) ) { + // throw exception + } + + if ( ! isset( $map['data_type'] ) ) { + // throw exception + } + + if ( isset( $map['metric_type'] ) + && $map['metric_type'] != 'calculated' + && ! isset( $map['column'] ) ) + { + + // throw exception + + } + + if ( isset( $map['metric_type'] ) + && $map['metric_type'] === 'calculated' + && ! isset( $map['child_metrics'] ) ) + { + + // throw exception + + } + + if ( isset( $map['metric_type'] ) + && $map['metric_type'] === 'calculated' + && ! isset( $map['formula'] ) ) + { + + // throw exception + + } + + $definition = array( + 'name' => $map['name'], + 'class' => 'base.configurableMetric', + 'params' => $map, + 'label' => $map['label'], + 'description' => $map['description'], + 'group' => $map['group'] + ); + //print_r($definition); + $this->metrics[ $map['name'] ][] = $definition; + + } + + /** + * Register a dimension + * + * registers a dimension for use by metrics in producing results sets. + * + * @param $dim_name string + * @param $entity_names string||array the names of entity housing the dimension. uses module.name format + * @param $column string the name of the column that represents the dimension + * @param $family string the name of the group or family that this dimension belongs to. optional. + * @param $description string a short description of this metric, used in various interfaces. + * @param $label string the lable of the dimension + * @param $foreign_key_name the name of the foreign key column that should + * be used to relate the metric entity to the dimension's entity. + * If one is not specfied, metrics will use any valid foreign key column they can find. + * Specifying this is important when the same column in a table is used by + * two different dimensions but the meaning of the column differs based on the value of the foreign key. + * a good example is the page_title column in the documents table. It is used by three dimensions: + * pageTitle, entryPageTitle, and existPageTitle. + * @param $denormalized boolean flag marks the dimension as being denormalized into a fact table + * as opposed to being housed in a related table. + */ + function registerDimension( + $dim_name, $entity_names, $column, $label = '', $family, + $description = '', $foreign_key_name = '', + $denormalized = false, $data_type = 'string') { + + if ( ! is_array( $entity_names ) ) { + $entity_names = array($entity_names); + } + + foreach ($entity_names as $entity) { + + $dim = array( + 'family' => $family, + 'name' => $dim_name, + 'entity' => $entity, + 'column' => $column, + 'label' => $label, + 'description' => $description, + 'foreign_key_name' => $foreign_key_name, + 'data_type' => $data_type, + 'denormalized' => $denormalized + ); + + if ($denormalized) { + $this->denormalizedDimensions[$dim_name][$entity] = $dim; + } else { + $this->dimensions[$dim_name] = $dim; + } + } + } + + function registerActions() { + + return false; + } + + + /** + * Registers an Action Controller + * + * @param $action_name string the name of the action used as the value in the 'do' url param + * @param $class_name string the name of the controller class + * @param $file string the path to the file housing the class + * + */ + protected function registerAction( $action_name, $class_name, $file = '' ) { + + $s = owa_coreAPI::serviceSingleton(); + $s->setMapValue( 'actions', $action_name, array( 'class_name' => $class_name, 'file' => $file ) ); + + } + + function registerCliCommand($command, $class) { + + $this->cli_commands[$command] = $class; + } + + function registerFormatter($type, $formatter) { + + $this->formatters[$type] = $formatter; + } + + function registerApiMethod($api_method_name, $user_function, $argument_names, $file = '', $required_capability = '') { + + $map = array('callback' => $user_function, 'args' => $argument_names, 'file' => $file); + + if ($required_capability) { + $map['required_capability'] = $required_capability; + } + + $this->api_methods[$api_method_name] = $map; + } + + function registerImplementation($type, $name, $class_name, $file) { + + $s = owa_coreAPI::serviceSingleton(); + $class_info = array($class_name, $file); + $s->setMapValue($type, $name, $class_info); + } + + function registerBackgroundJob($name, $command, $cron_tab, $max_processes = 1) { + + $job = array('name' => $name, + 'cron_tab' => $cron_tab, + 'command' => $command, + 'max_processes' => $max_processes); + + $s = owa_coreAPI::serviceSingleton(); + $s->setMapValue('background_jobs', $name, $job); + } + + /** + * Register Environmental Tracking Properties + * + * These are tracking properties that are derived from the Server environment + * and should be added to all tracking tracking events as they are recieved. + * + * + * @var $type string the type of tracking property environmental|regular|derived + * + * environmental = properties that are only dependant on the PHP SERVER environment. + * regular = properties that are set by clients + * derived = properties that are derived from or dependant on other properties + * + * @var $properties array an associative array of tracking properties + * + * Example: + * + * 'REMOTE_HOST' => array( + * 'default_value' => array( 'owa_trackingEventHelpers::remoteHostDefault' ), + * 'required' => true, + * 'data_type' => 'string', + * 'filter' => true + * ) + * + * + * The key of the array is the name the property + */ + + function registerTrackingProperties( $type, $properties = array() ) { + + switch( strtolower( $type ) ) { + + case 'environmental': + $map_key = 'tracking_properties_environmental'; + break; + + case 'regular': + $map_key = 'tracking_properties_regular'; + break; + + case 'derived': + $map_key = 'tracking_properties_derived'; + break; + + default: + $map_key = ''; + } + + if ( is_array( $properties ) && $map_key ) { + + $s = owa_coreAPI::serviceSingleton(); + + foreach ( $properties as $k => $property ) { + + $s->setMapValue( $map_key, $k, $property); + } + } + } + + /** + * Abstract method for registering individual API methods + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerApiMethods() { + + return false; + } + + /** + * Abstract method for registering individual CLI commands + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerCliCommands() { + + return false; + } + + /** + * Abstract method for registering individual Metrics + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerMetrics() { + + return false; + } + + /** + * Abstract method for registering individual CLI commands + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerDimensions() { + + return false; + } + + /** + * Abstract method for registering individual Filter Methods + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerFilters() { + + return false; + } + + /** + * Abstract method for registering individual Filter Methods + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerBackgroundJobs() { + + return false; + } + + /** + * Abstract method for registering package files to build + * + * This method is called by a module's constructor + * and should be redefined in a concrete module class. + */ + function registerBuildPackages() { + + return false; + } + + /** + * Registers a new package of files to be built by + * the 'build' CLI command. + * + * $package array the package array takes the form of + * + * 'name' => 'mypackage' + * 'output_dir' => '/path/to/output' + * 'files' => array('foo' => array('path' => '/path/to/file/file.js', + * 'compression' => 'minify')) + */ + protected function registerBuildPackage( $package ) { + + if (! isset( $package['name'] ) ) { + + throw exception('Build Package does not have a name.'); + } + + if (! isset( $package['output_dir'] ) ) { + + throw exception('Build Package does not have an output directory.'); + } else { + //check for trailing slash + $check = substr($package['output_dir'], -1, 1); + if ($check != '/') { + $package['output_dir'] = $package['output_dir'].'/'; + } + } + + if (! isset( $package['files'] ) ) { + + throw exception('Build Package does not any files.'); + } + + // filter the pcakge in case other modules want to change something. + $eq = owa_coreAPI::getEventDispatch(); + $package = $eq->filter( 'register_build_package', $package ); + + $s = owa_coreAPI::serviceSingleton(); + $s->setMapValue('build_packages', $package['name'], $package); + } + + + /** + * Retuns internal struct array used for saving link infos + * @param string $ref + * @param string $anchortext + * @param integer $order + * @param string $priviledge + * @return array + */ + private function getLinkStruct($ref,$anchortext,$order,$priviledge) { + return array('ref' => $ref, + 'anchortext' => $anchortext, + 'order' => $order, + 'priviledge' => $priviledge); + } + + protected function registerEventQueue( $name, $map ) { + + $map['queue_name'] = $name; + $s = owa_coreAPI::serviceSingleton(); + $s->setMapValue( 'event_queues', $name, $map ); + } + +} + ?> \ No newline at end of file diff --git a/owa_mw.php b/owa_mw.php index 34d5a54cf..722da3b70 100644 --- a/owa_mw.php +++ b/owa_mw.php @@ -1,66 +1,66 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_mw extends owa_client { - - function __construct($config = null) { - - return parent::__construct($config); - } - - function owa_mw($config = null) { - - return owa_mw::__construct($config); - } - - /** - * OWA Singleton Method - * - * Makes a singleton instance of OWA using the config array - */ - function singleton($config = null) { - - static $owa; - - if(!empty($owa)) { - return $owa; - } else { - $owa = new owa_mw($config); - return $owa; - } - } - - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_mw extends owa_client { + + function __construct($config = null) { + + return parent::__construct($config); + } + + function owa_mw($config = null) { + + return owa_mw::__construct($config); + } + + /** + * OWA Singleton Method + * + * Makes a singleton instance of OWA using the config array + */ + function singleton($config = null) { + + static $owa; + + if(!empty($owa)) { + return $owa; + } else { + $owa = new owa_mw($config); + return $owa; + } + } + + +} + ?> \ No newline at end of file diff --git a/owa_observer.php b/owa_observer.php index f263669bc..420176bf2 100644 --- a/owa_observer.php +++ b/owa_observer.php @@ -1,78 +1,78 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_observer extends owa_base { - - /** - * The type of event that an observer would want to hear about. - * - * @var array - * @access private - */ - var $_event_type = array(); - - var $id; - - /** - * Event Message - * - * @var array - */ - var $m; - - /** - * Creates a new basic Log_observer instance. - * - * @param integer $priority The highest priority at which to receive - * log event notifications. - * - * @access public - */ - function __construct() { - $this->id = md5(microtime()); - } - - function handleEvent($action) { - - $data = owa_coreAPI::performAction($action, array('event' => $this->m)); - return owa_coreAPI::debug(sprintf("Handled Event. Action: %s", $action)); - - } - - function sendMail($email_address, $subject, $msg) { - - mail($email_address, $subject, $msg); - owa_coreAPI::debug('Sent e-mail with subject of "'.$subject.'" to: '.$email_address); - return; - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_observer extends owa_base { + + /** + * The type of event that an observer would want to hear about. + * + * @var array + * @access private + */ + var $_event_type = array(); + + var $id; + + /** + * Event Message + * + * @var array + */ + var $m; + + /** + * Creates a new basic Log_observer instance. + * + * @param integer $priority The highest priority at which to receive + * log event notifications. + * + * @access public + */ + function __construct() { + $this->id = md5(microtime()); + } + + function handleEvent($action) { + + $data = owa_coreAPI::performAction($action, array('event' => $this->m)); + return owa_coreAPI::debug(sprintf("Handled Event. Action: %s", $action)); + + } + + function sendMail($email_address, $subject, $msg) { + + mail($email_address, $subject, $msg); + owa_coreAPI::debug('Sent e-mail with subject of "'.$subject.'" to: '.$email_address); + return; + } + +} + ?> \ No newline at end of file diff --git a/owa_php.php b/owa_php.php index 045e2f947..49f93014b 100644 --- a/owa_php.php +++ b/owa_php.php @@ -1,61 +1,61 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_php extends owa_client { - - function __construct($config = null) { - - return parent::__construct($config); - } - - /** - * OWA Singleton Method - * - * Makes a singleton instance of OWA using the config array - */ - function singleton($config = null) { - - static $owa; - - if(!empty($owa)) { - return $owa; - } else { - return new owa_php($config); - } - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_php extends owa_client { + + function __construct($config = null) { + + return parent::__construct($config); + } + + /** + * OWA Singleton Method + * + * Makes a singleton instance of OWA using the config array + */ + function singleton($config = null) { + + static $owa; + + if(!empty($owa)) { + return $owa; + } else { + return new owa_php($config); + } + } +} + ?> \ No newline at end of file diff --git a/owa_reportController.php b/owa_reportController.php index c5e528f1f..b501a24da 100644 --- a/owa_reportController.php +++ b/owa_reportController.php @@ -1,195 +1,195 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - -class owa_reportController extends owa_adminController { - - /** - * Constructor - * - * @param array $params - * @return - */ - function __construct($params) { - $this->setControllerType('report'); - $this->setRequiredCapability('view_reports'); - parent::__construct($params); - - // set a siteId is none is set on the request params - $siteId = $this->getCurrentSiteId(); - - if ( ! $siteId ) { - //$siteId = $this->getDefaultSiteId(); - } - - $this->setParam( 'siteId', $siteId ); - } - - - /** - * Pre Action - * Current user is fully authenticated and loaded by this point - * - */ - function pre() { - - $sites = $this->getSitesAllowedForCurrentUser(); - $this->set('sites', $sites); - - $this->set( 'currentSiteId', $this->getParam('siteId') ); - - // pass full set of params to view - $this->data['params'] = $this->params; - - // setup the time period object in $this->period - $this->setPeriod(); - // check to see if the period is a default period. TODO move this ot view where needed. - $this->set('is_default_period', $this->period->isDefaultPeriod() ); - $this->setView('base.report'); - $this->setViewMethod('delegate'); - - $this->dom_id = str_replace('.', '-', $this->getParam('do')); - $this->data['dom_id'] = $this->dom_id; - $this->data['do'] = $this->getParam('do'); - $nav = owa_coreAPI::getGroupNavigation('Reports'); - // setup tabs - $siteId = $this->get('siteId'); - if ($siteId) { - $gm = owa_coreAPI::supportClassFactory('base', 'goalManager', $siteId); - - $tabs = array(); - $site_usage = array( - 'tab_label' => 'Site Usage', - 'metrics' => 'visits,pagesPerVisit,visitDuration,bounceRate,uniqueVisitors', - 'sort' => 'visits-', - 'trendchartmetric' => 'visits' - ); - - $tabs['site_usage'] = $site_usage; - - // ecommerce tab - if ( owa_coreAPI::getSiteSetting( $this->getParam('siteId'), 'enableEcommerceReporting') ) { - - $ecommerce = array( - 'tab_label' => 'e-commerce', - 'metrics' => 'visits,transactions,transactionRevenue,revenuePerVisit,revenuePerTransaction,ecommerceConversionRate', - 'sort' => 'transactionRevenue-', - 'trendchartmetric' => 'transactions' - ); - - $tabs['ecommerce'] = $ecommerce; - } - $goal_groups = $gm->getActiveGoalGroups(); - - if ( $goal_groups ) { - foreach ($goal_groups as $group) { - $goal_metrics = 'visits'; - $active_goals = $gm->getActiveGoalsByGroup($group); - - if ( $active_goals ) { - - foreach ($active_goals as $goal) { - $goal_metrics .= sprintf(',goal%sCompletions', $goal); - } - } - - $goal_metrics .= ',goalValueAll'; - $goal_group = array( - 'tab_label' => $gm->getGoalGroupLabel($group), - 'metrics' => $goal_metrics, - 'sort' => 'goalValueAll-', - 'trendchartmetric' => 'visits' - ); - $name = 'goal_group_'.$group; - $tabs[$name] = $goal_group; - } - } - - $this->set('tabs', $tabs); - $this->set('tabs_json', json_encode($tabs)); - - - - if ( ! owa_coreAPI::getSiteSetting( $this->getParam( 'siteId' ), 'enableEcommerceReporting' ) ) { - - unset($nav['Ecommerce']); - } - } - - //$this->body->set('sub_nav', owa_coreAPI::getNavigation($this->get('nav_tab'), 'sub_nav')); - - - $this->set('top_level_report_nav', $nav); - - - } - - function post() { - - return; - } - - function setTitle($title, $suffix = '') { - - $this->set('title', $title); - $this->set('titleSuffix', $suffix); - } - - /** - * Chooses a siteId from a list of AllowedSites - * - * needed jsut in case a siteId is not passed on the request. - * @return string - */ - protected function getDefaultSiteId() { - - $db = owa_coreAPI::dbSingleton(); - $db->select('site_id'); - $db->from('owa_site'); - $db->limit(1); - $ret = $db->getOneRow(); - - return $ret['site_id']; - } - - protected function hideReportingNavigation() { - - $this->set('hideReportingNavigation', true); - } - - protected function hideSitesFilter() { - - $this->set('hideSitesFilter', true); - } -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + +class owa_reportController extends owa_adminController { + + /** + * Constructor + * + * @param array $params + * @return + */ + function __construct($params) { + $this->setControllerType('report'); + $this->setRequiredCapability('view_reports'); + parent::__construct($params); + + // set a siteId is none is set on the request params + $siteId = $this->getCurrentSiteId(); + + if ( ! $siteId ) { + //$siteId = $this->getDefaultSiteId(); + } + + $this->setParam( 'siteId', $siteId ); + } + + + /** + * Pre Action + * Current user is fully authenticated and loaded by this point + * + */ + function pre() { + + $sites = $this->getSitesAllowedForCurrentUser(); + $this->set('sites', $sites); + + $this->set( 'currentSiteId', $this->getParam('siteId') ); + + // pass full set of params to view + $this->data['params'] = $this->params; + + // setup the time period object in $this->period + $this->setPeriod(); + // check to see if the period is a default period. TODO move this ot view where needed. + $this->set('is_default_period', $this->period->isDefaultPeriod() ); + $this->setView('base.report'); + $this->setViewMethod('delegate'); + + $this->dom_id = str_replace('.', '-', $this->getParam('do')); + $this->data['dom_id'] = $this->dom_id; + $this->data['do'] = $this->getParam('do'); + $nav = owa_coreAPI::getGroupNavigation('Reports'); + // setup tabs + $siteId = $this->get('siteId'); + if ($siteId) { + $gm = owa_coreAPI::supportClassFactory('base', 'goalManager', $siteId); + + $tabs = array(); + $site_usage = array( + 'tab_label' => 'Site Usage', + 'metrics' => 'visits,pagesPerVisit,visitDuration,bounceRate,uniqueVisitors', + 'sort' => 'visits-', + 'trendchartmetric' => 'visits' + ); + + $tabs['site_usage'] = $site_usage; + + // ecommerce tab + if ( owa_coreAPI::getSiteSetting( $this->getParam('siteId'), 'enableEcommerceReporting') ) { + + $ecommerce = array( + 'tab_label' => 'e-commerce', + 'metrics' => 'visits,transactions,transactionRevenue,revenuePerVisit,revenuePerTransaction,ecommerceConversionRate', + 'sort' => 'transactionRevenue-', + 'trendchartmetric' => 'transactions' + ); + + $tabs['ecommerce'] = $ecommerce; + } + $goal_groups = $gm->getActiveGoalGroups(); + + if ( $goal_groups ) { + foreach ($goal_groups as $group) { + $goal_metrics = 'visits'; + $active_goals = $gm->getActiveGoalsByGroup($group); + + if ( $active_goals ) { + + foreach ($active_goals as $goal) { + $goal_metrics .= sprintf(',goal%sCompletions', $goal); + } + } + + $goal_metrics .= ',goalValueAll'; + $goal_group = array( + 'tab_label' => $gm->getGoalGroupLabel($group), + 'metrics' => $goal_metrics, + 'sort' => 'goalValueAll-', + 'trendchartmetric' => 'visits' + ); + $name = 'goal_group_'.$group; + $tabs[$name] = $goal_group; + } + } + + $this->set('tabs', $tabs); + $this->set('tabs_json', json_encode($tabs)); + + + + if ( ! owa_coreAPI::getSiteSetting( $this->getParam( 'siteId' ), 'enableEcommerceReporting' ) ) { + + unset($nav['Ecommerce']); + } + } + + //$this->body->set('sub_nav', owa_coreAPI::getNavigation($this->get('nav_tab'), 'sub_nav')); + + + $this->set('top_level_report_nav', $nav); + + + } + + function post() { + + return; + } + + function setTitle($title, $suffix = '') { + + $this->set('title', $title); + $this->set('titleSuffix', $suffix); + } + + /** + * Chooses a siteId from a list of AllowedSites + * + * needed jsut in case a siteId is not passed on the request. + * @return string + */ + protected function getDefaultSiteId() { + + $db = owa_coreAPI::dbSingleton(); + $db->select('site_id'); + $db->from('owa_site'); + $db->limit(1); + $ret = $db->getOneRow(); + + return $ret['site_id']; + } + + protected function hideReportingNavigation() { + + $this->set('hideReportingNavigation', true); + } + + protected function hideSitesFilter() { + + $this->set('hideSitesFilter', true); + } +} + ?> \ No newline at end of file diff --git a/owa_requestContainer.php b/owa_requestContainer.php index 2d1d0b9d2..d237fcfa3 100644 --- a/owa_requestContainer.php +++ b/owa_requestContainer.php @@ -1,316 +1,316 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_requestContainer { - - var $cli_args; - var $is_https; - var $owa_params = array(); - var $cookies = array(); - var $owa_cookies = array(); - var $session = array(); - var $request = array(); - var $server; - var $guid; - var $state; - var $request_type = ''; - var $timestamp; - var $current_url; - - /** - * Constructor - * - */ - function __construct() { - - $this->timestamp = time(); - $this->guid = owa_lib::generateRandomUid(); - - // php's server variables - $this->server = $_SERVER; - - // files - if (!empty($_FILES)) { - $this->files = $_FILES; - } - - // setup cookies - $this->cookies = array(); - - // look for access to the raw HTTP cookie string. This is needed becuause OWA can set settings cookies - // with the same name under different subdomains. Multiple cookies with the same name are not - // available under $_COOKIE. Therefor OWA's cookie conainter must be an array of arrays. - if ( isset( $_SERVER['HTTP_COOKIE'] ) && strpos( $_SERVER['HTTP_COOKIE'], ';') ) { - - $raw_cookie_array = explode(';', $_SERVER['HTTP_COOKIE']); - - foreach($raw_cookie_array as $raw_cookie ) { - - $nvp = explode( '=', trim( $raw_cookie ) ); - $this->cookies[ $nvp[0] ][] = urldecode($nvp[1]); - } - - } else { - // just use the normal cookie global - if ( $_COOKIE && is_array($_COOKIE) ) { - - foreach ($_COOKIE as $n => $v) { - // hack against other frameworks sanitizing cookie data and blowing away our '>' delimiter - // this should be removed once all cookies are using json format. - if (strpos($v, '>')) { - $v = str_replace(">", ">", $v); - } - - $cookies[ $n ][] = $v; - } - } - } - - // populate owa_cookie container with just the cookies that have the owa namespace. - $this->owa_cookies = owa_lib::stripParams( $this->cookies, owa_coreAPI::getSetting('base', 'ns') ); - - - // session - if (!empty($_SESSION)) { - $this->session = $_SESSION; - } - - /* STATE CONTAINER */ - - // state - $this->state = owa_coreAPI::supportClassFactory('base', 'state'); - // merges session - if (!empty($this->session)) { - $this->state->addStores(owa_lib::stripParams($this->session, owa_coreAPI::getSetting('base', 'ns'))); - } - - // merges cookies - foreach ( $this->owa_cookies as $k => $owa_cookie ) { - - $this->state->setInitialState( $k, $owa_cookie ); - } - - // create request params from GET or POST or CLI args - $params = array(); - - // use GET vars as the base for the request - if ( isset( $_GET ) && ! empty( $_GET ) ) { - // get params from _GET - $params = $_GET; - - $this->request_type = 'get'; - } - - // merge in POST vars. GET and POST can occure on the same request. - if ( isset( $_POST ) && ! empty( $_POST ) ) { - // get params from _GET - $params = array_merge( $params, $_POST); - - $this->request_type = 'post'; - } - - // look for command line arguments in the 'argv' index. - if ( ! $this->request_type && isset( $_SERVER['argv'] ) ) { - - $this->cli_args = $_SERVER['argv']; - - // parse arguments into key value pairs - for ( $i=1; $i < count( $this->cli_args ); $i++ ) { - $it = explode( "=", $this->cli_args[$i] ); - - if ( isset( $it[1] ) ) { - $params[ $it[0] ] = $it[1]; - } else { - $params[ $it[0] ] = ''; - } - } - - $this->request_type = 'cli'; - } - - if ( $this->request_type != 'cli' ) { - - $this->current_url = owa_lib::get_current_url(); - } - - // Clean Input arrays - if ( $params ) { - - if ( ! owa_coreAPI::getSetting('base', 'tracking_mode') ) { - - $params = owa_sanitize::cleanInput( $params, array( 'remove_html' => true, 'escape_html' => false ) ); - - } - if ( is_array( $params ) && ! empty( $params ) ) { - - $this->request = $params; - } - } - - // get namespace - $ns = owa_coreAPI::getSetting('base', 'ns'); - // strip action and do params of nasty include exploits. - if (array_key_exists( $ns.'action', $this->request)) { - - $this->request[$ns.'action'] = owa_lib::fileInclusionFilter($this->request[$ns.'action']); - } - - if (array_key_exists($ns.'do', $this->request)) { - - $this->request[$ns.'do'] = owa_lib::fileInclusionFilter($this->request[$ns.'do']); - } - - // strip owa namespace - $this->owa_params = owa_lib::stripParams($this->request, $ns); - - // translate certain request variables that are reserved in javascript - $this->owa_params = owa_lib::rekeyArray($this->owa_params, array_flip(owa_coreAPI::getSetting('base', 'reserved_words'))); - - // set https flag - if( isset($_SERVER['HTTPS'] ) ) { - $this->is_https = true; - } - } - - function getParam($name) { - - if (array_key_exists($name, $this->owa_params)) { - return $this->owa_params[$name]; - } else { - return false; - } - - } - - function setParam($name, $value) { - - $this->owa_params[$name] = $value; - return true; - } - - function getCookie($name) { - - if (array_key_exists($name, $this->cookies)) { - return $this->cookies[$name]; - } else { - return false; - } - - } - - function getRequestParam($name) { - - if (array_key_exists($name, $this->request)) { - return $this->request[$name]; - } else { - return false; - } - } - - function getAllRequestParams() { - - return $this->request; - } - - function getAllOwaParams() { - - return $this->owa_params; - } - - function mergeParams($params) { - - $this->owa_params = array_merge($this->owa_params, $params); - return; - } - - function getServerParam($name) { - - if (array_key_exists($name, $this->server)) { - return $this->server[$name]; - } else { - return false; - } - } - - function decodeRequestParams() { - - $params = array(); - // Apply caller specific params - foreach ($this->owa_params as $k => $v) { - if (is_array($v)) { - array_walk_recursive($v, array($this, 'arrayUrlDecode')); - $params[$k] = $v; - } else { - $params[$k] = urldecode($v); - } - } - - // clean params after decode - //$params = owa_lib::inputFilter($params); - // replace owa params - $this->owa_params = $params; - //debug - owa_coreAPI::debug('decoded OWA params: '. print_r($this->owa_params, true)); - return; - - } - - function arrayUrlDecode(&$val, $index) { - urldecode($val); - } - - function getOwaCookie($name) { - - if (array_key_exists($name, $this->owa_cookies)) { - return $this->owa_cookies[$name]; - } else { - return false; - } - - } - - public function getTimestamp() { - - return $this->timestamp; - } - - public function getCurrentUrl() { - - return $this->current_url; - } - - public function getRequestType() { - - return $this->request_type; - } - -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_requestContainer { + + var $cli_args; + var $is_https; + var $owa_params = array(); + var $cookies = array(); + var $owa_cookies = array(); + var $session = array(); + var $request = array(); + var $server; + var $guid; + var $state; + var $request_type = ''; + var $timestamp; + var $current_url; + + /** + * Constructor + * + */ + function __construct() { + + $this->timestamp = time(); + $this->guid = owa_lib::generateRandomUid(); + + // php's server variables + $this->server = $_SERVER; + + // files + if (!empty($_FILES)) { + $this->files = $_FILES; + } + + // setup cookies + $this->cookies = array(); + + // look for access to the raw HTTP cookie string. This is needed becuause OWA can set settings cookies + // with the same name under different subdomains. Multiple cookies with the same name are not + // available under $_COOKIE. Therefor OWA's cookie conainter must be an array of arrays. + if ( isset( $_SERVER['HTTP_COOKIE'] ) && strpos( $_SERVER['HTTP_COOKIE'], ';') ) { + + $raw_cookie_array = explode(';', $_SERVER['HTTP_COOKIE']); + + foreach($raw_cookie_array as $raw_cookie ) { + + $nvp = explode( '=', trim( $raw_cookie ) ); + $this->cookies[ $nvp[0] ][] = urldecode($nvp[1]); + } + + } else { + // just use the normal cookie global + if ( $_COOKIE && is_array($_COOKIE) ) { + + foreach ($_COOKIE as $n => $v) { + // hack against other frameworks sanitizing cookie data and blowing away our '>' delimiter + // this should be removed once all cookies are using json format. + if (strpos($v, '>')) { + $v = str_replace(">", ">", $v); + } + + $cookies[ $n ][] = $v; + } + } + } + + // populate owa_cookie container with just the cookies that have the owa namespace. + $this->owa_cookies = owa_lib::stripParams( $this->cookies, owa_coreAPI::getSetting('base', 'ns') ); + + + // session + if (!empty($_SESSION)) { + $this->session = $_SESSION; + } + + /* STATE CONTAINER */ + + // state + $this->state = owa_coreAPI::supportClassFactory('base', 'state'); + // merges session + if (!empty($this->session)) { + $this->state->addStores(owa_lib::stripParams($this->session, owa_coreAPI::getSetting('base', 'ns'))); + } + + // merges cookies + foreach ( $this->owa_cookies as $k => $owa_cookie ) { + + $this->state->setInitialState( $k, $owa_cookie ); + } + + // create request params from GET or POST or CLI args + $params = array(); + + // use GET vars as the base for the request + if ( isset( $_GET ) && ! empty( $_GET ) ) { + // get params from _GET + $params = $_GET; + + $this->request_type = 'get'; + } + + // merge in POST vars. GET and POST can occure on the same request. + if ( isset( $_POST ) && ! empty( $_POST ) ) { + // get params from _GET + $params = array_merge( $params, $_POST); + + $this->request_type = 'post'; + } + + // look for command line arguments in the 'argv' index. + if ( ! $this->request_type && isset( $_SERVER['argv'] ) ) { + + $this->cli_args = $_SERVER['argv']; + + // parse arguments into key value pairs + for ( $i=1; $i < count( $this->cli_args ); $i++ ) { + $it = explode( "=", $this->cli_args[$i] ); + + if ( isset( $it[1] ) ) { + $params[ $it[0] ] = $it[1]; + } else { + $params[ $it[0] ] = ''; + } + } + + $this->request_type = 'cli'; + } + + if ( $this->request_type != 'cli' ) { + + $this->current_url = owa_lib::get_current_url(); + } + + // Clean Input arrays + if ( $params ) { + + if ( ! owa_coreAPI::getSetting('base', 'tracking_mode') ) { + + $params = owa_sanitize::cleanInput( $params, array( 'remove_html' => true, 'escape_html' => false ) ); + + } + if ( is_array( $params ) && ! empty( $params ) ) { + + $this->request = $params; + } + } + + // get namespace + $ns = owa_coreAPI::getSetting('base', 'ns'); + // strip action and do params of nasty include exploits. + if (array_key_exists( $ns.'action', $this->request)) { + + $this->request[$ns.'action'] = owa_lib::fileInclusionFilter($this->request[$ns.'action']); + } + + if (array_key_exists($ns.'do', $this->request)) { + + $this->request[$ns.'do'] = owa_lib::fileInclusionFilter($this->request[$ns.'do']); + } + + // strip owa namespace + $this->owa_params = owa_lib::stripParams($this->request, $ns); + + // translate certain request variables that are reserved in javascript + $this->owa_params = owa_lib::rekeyArray($this->owa_params, array_flip(owa_coreAPI::getSetting('base', 'reserved_words'))); + + // set https flag + if( isset($_SERVER['HTTPS'] ) ) { + $this->is_https = true; + } + } + + function getParam($name) { + + if (array_key_exists($name, $this->owa_params)) { + return $this->owa_params[$name]; + } else { + return false; + } + + } + + function setParam($name, $value) { + + $this->owa_params[$name] = $value; + return true; + } + + function getCookie($name) { + + if (array_key_exists($name, $this->cookies)) { + return $this->cookies[$name]; + } else { + return false; + } + + } + + function getRequestParam($name) { + + if (array_key_exists($name, $this->request)) { + return $this->request[$name]; + } else { + return false; + } + } + + function getAllRequestParams() { + + return $this->request; + } + + function getAllOwaParams() { + + return $this->owa_params; + } + + function mergeParams($params) { + + $this->owa_params = array_merge($this->owa_params, $params); + return; + } + + function getServerParam($name) { + + if (array_key_exists($name, $this->server)) { + return $this->server[$name]; + } else { + return false; + } + } + + function decodeRequestParams() { + + $params = array(); + // Apply caller specific params + foreach ($this->owa_params as $k => $v) { + if (is_array($v)) { + array_walk_recursive($v, array($this, 'arrayUrlDecode')); + $params[$k] = $v; + } else { + $params[$k] = urldecode($v); + } + } + + // clean params after decode + //$params = owa_lib::inputFilter($params); + // replace owa params + $this->owa_params = $params; + //debug + owa_coreAPI::debug('decoded OWA params: '. print_r($this->owa_params, true)); + return; + + } + + function arrayUrlDecode(&$val, $index) { + urldecode($val); + } + + function getOwaCookie($name) { + + if (array_key_exists($name, $this->owa_cookies)) { + return $this->owa_cookies[$name]; + } else { + return false; + } + + } + + public function getTimestamp() { + + return $this->timestamp; + } + + public function getCurrentUrl() { + + return $this->current_url; + } + + public function getRequestType() { + + return $this->request_type; + } + +} + ?> \ No newline at end of file diff --git a/owa_template.php b/owa_template.php index 75e8c1a82..ed4f3a247 100755 --- a/owa_template.php +++ b/owa_template.php @@ -1,1055 +1,1055 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - -class owa_template extends Template { - - /** - * Configuration - * - * @var array - */ - var $config; - - var $theme_template_dir; - - var $module_local_template_dir; - - var $module_template_dir; - - var $e; - - var $period; - - /** - * Params passed by calling caller - * - * @var array - */ - var $caller_params; - - function __construct( $module = null, $caller_params = array() ) { - - $this->caller_params = $caller_params; - - $c = owa_coreAPI::configSingleton(); - $this->config = $c->fetch('base'); - - $this->e = owa_coreAPI::errorSingleton(); - - // set template dirs - if(!empty($caller_params['module'])): - $this->_setTemplateDir($module); - else: - $this->_setTemplateDir('base'); - endif; - - $this->time_now = owa_lib::time_now(); - } - - function _setTemplateDir($module) { - - // set module template dir - $this->module_template_dir = OWA_DIR.'modules'.'/' . $module . '/'.'templates'.'/'; - - // set module local template override dir - $this->module_local_template_dir = $this->module_template_dir.'local'.'/'; - - // set theme template dir - $this->theme_template_dir = OWA_THEMES_DIR.$this->config['theme'].'/'; - - return; - } - - function getTemplatePath($module, $file) { - - $this->_setTemplateDir($module); - - if ($file == null) { - owa_coreAPI::error('No template file was specified.'); - return false; - } else { - // check module's local modification template Directory - if (file_exists($this->module_local_template_dir.$file)) { - $fullfile = $this->module_local_template_dir.$file; - - // check theme's template Directory - } elseif(file_exists($this->theme_template_dir.$file)) { - $fullfile = $this->theme_template_dir.$file; - - // check module's template directory - } elseif(file_exists($this->module_template_dir.$file)) { - $fullfile = $this->module_template_dir.$file; - - // throw error - } else { - $this->e->err(sprintf('%s was not found in any template directory.', $file)); - return false; - } - return $fullfile; - } - - - - } - - /** - * Set the template file - * @depricated - * @param string $file - */ - function set_template($file = null) { - - if (!$file): - owa_coreAPI::error('No template file was specified.'); - return false; - else: - // check module's local modification template Directory - if (file_exists($this->module_local_template_dir.$file)): - $this->file = $this->module_local_template_dir.$file; - - // check theme's template Directory - elseif(file_exists($this->theme_template_dir.$file)): - $this->file = $this->theme_template_dir.$file; - - // check module's template directory - elseif(file_exists($this->module_template_dir.$file)): - $this->file = $this->module_template_dir.$file; - - // throw error - else: - $this->e->err(sprintf('%s was not found in any template directory.', $file)); - return false; - endif; - - return true; - endif; - } - - function setTemplateFile($module, $file) { - - //choose file - $filepath = $this->getTemplatePath($module, $file); - //set template - if ($filepath) { - $this->file = $filepath; - } - } - - /** - * Truncate string - * - * @param string $str - * @param integer $length - * @param string $trailing - * @return string - */ - function truncate ($str, $length=10, $trailing='...') { - - return owa_lib::truncate ($str, $length, $trailing); - } - - function get_month_label($month) { - - return owa_lib::get_month_label($month); - } - - /** - * Chooses the right icon based on browser type - * - * @param unknown_type $browser_type - * @return unknown - */ - function choose_browser_icon($browser_type, $height= '32', $width='') { - - $default_location = 'base/i/browsers/128x128/'; - - $icons = array( - - 'internet explorer' => $default_location . 'ie.png', - 'opera mini' => $default_location . 'opera.png', - 'unknown browser' => $default_location . 'default.png' - - ); - - $file = $default_location . strtolower( $browser_type ) . '.png' ; - - if ( file_exists( OWA_MODULES_DIR . $file ) ) { - - $file = $file; - - } else if ( isset( $icons[ strtolower($browser_type) ] ) ) { - - $file = $icons[ strtolower($browser_type) ]; - - } else { - - $file = $icons['unknown browser']; - } - - return sprintf( '%s', - $browser_type, - $this->makeImageLink( $file ), - $width, - $height - ); - - } - - function getBrowserIcon($browser_family, $size = '128x128', $module = 'base') { - - if ($browser_family) { - $browser_family = strtolower($browser_family); - } - - - if (file_exists(OWA_MODULES_DIR.$module.'/i/browsers/'.$size.'/'.$browser_family.'.png')) { - return $this->makeImageLink('base/i/browsers/'.$size.'/'.$browser_family.'.png'); - } else { - return $this->makeImageLink('base/i/browsers/'.$size.'/default.png'); - } - } - - - function makeLinkQueryString($query_params) { - - $new_query_params = array(); - - //Load params passed by caller - if (!empty($this->caller_params)): - foreach ($this->caller_params as $name => $value) { - if (!empty($value)): - $new_query_params[$name] = $value; - endif; - } - endif; - - // Load overrides - if (!empty($query_params)): - foreach ($query_params as $name => $value) { - if (!empty($value)): - $new_query_params[$name] = $value; - endif; - } - endif; - - // Construct GET request - if (!empty($new_query_params)): - foreach ($new_query_params as $name => $value) { - if (!empty($value)): - $get .= $name . "=" . $value . "&"; - endif; - } - endif; - - return $get; - - } - - /** - * Makes navigation links by checking whether or not the view - * that is rendering the template is not the view being refered to in the link. - * - * @param array navigation array - */ - function makeNavigation($nav, $id = '', $class = '', $li_template = '
  • %s
  • ', $li_class = '') { - - $ul = sprintf('
      ', $id, $class); - - if (!empty($nav)): - - $navigation = $ul; - - foreach($nav as $k => $v) { - - $navigation .= sprintf($li_template, $li_class, $this->makeLink(array('do' => $v['ref']), true), $v['anchortext']); - - } - - $navigation .= '
    '; - - return $navigation; - else: - return false; - endif; - - } - - function makeTwoLevelNav($links) { - print_r($links); - $navigation = '
      '; - - foreach($links as $k => $v) { - - if (!empty($v['subgroup'])): - $sub_nav = $this->makeNavigation($v['subgroup']); - - $navigation .= sprintf('
    • %s
    • ', - $this->makeLink(array('do' => $v['ref']), true), - $v['anchortext'], $sub_nav); - else: - - $navigation .= sprintf('
    • ', - $this->makeLink(array('do' => $v['ref']), true), - $v['anchortext']); - - endif; - - } - - $navigation .= '
    '; - - return $navigation; - - } - - function daysAgo($time) { - - $now = mktime(23, 59, 59, $this->time_now['month'], $this->time_now['day'], $this->time_now['year']); - - $days = round(($now - $time) / (3600*24)); - - switch ($days) { - - case 1: - return $days . " day ago"; - - default: - return $days . " days ago"; - } - - } - - /** - * @depricated - * @todo remove - */ - function getAuthStatus() { - - if (!class_exists('owa_auth')) { - require_once(OWA_BASE_DIR.'/owa_auth.php'); - } - - $auth = &owa_auth::get_instance(); - return $auth->auth_status; - } - - function makeWikiLink($page) { - - return sprintf($this->config['owa_wiki_link_template'], $page); - } - - /** - * Returns Namespace value to template - * - * @return string - */ - function getNs() { - - return $this->config['ns']; - } - - function makeParamString($params = array(), $add_state = false, $format = 'query', $namespace = true) { - - $all_params = array(); - - // merge in state params - if ($add_state) { - $all_params = array_merge($all_params, $this->getAllStateParams()); - } - //merge in params - $all_params = array_merge($all_params, $params); - - switch($format) { - - case 'query': - - $get = ''; - - $count = count($all_params); - - $i = 0; - - foreach ($all_params as $n => $v) { - - $get .= owa_coreAPI::getSetting('base','ns').$n.'='.$v; - - $i++; - - if ($i < $count): - $get .= "&"; - endif; - } - - $string= $get; - - break; - - case 'cookie': - - $string = owa_lib::implode_assoc('=>', '|||', $all_params); - break; - - case 'json': - - $string = json_encode( $all_params ); - - break; - } - - - return $string; - - } - - function getAllStateParams() { - - $all_params = array(); - - if (!empty($this->caller_params['link_state'])) { - $all_params = array_merge($all_params, $this->caller_params['link_state']); - } - - // add in period properties if available - $period = $this->get('timePeriod'); - - if (!empty($period)) { - $all_params = array_merge($all_params, $period->getPeriodProperties()); - //print_r($all_params); - } - - return $all_params; - } - - - /** - * Makes Links, adds state to links optionaly. - * - * @param array $params - * @param boolean $add_state - * @return string - */ - function makeLink($params = array(), $add_state = false, $url = '', $xml = false, $add_nonce = false) { - - $all_params = array(); - - //Loads link state passed by caller - if ($add_state == true) { - if (!empty($this->caller_params['link_state'])) { - $all_params = array_merge($all_params, $this->caller_params['link_state']); - } - - // add in period properties if available - $period = $this->get('timePeriod'); - - if (!empty($period)) { - $all_params = array_merge($all_params, $period->getPeriodProperties()); - - } - } - - // Load overrides - if (!empty($params)) { - $params = array_filter($params); - $all_params = array_merge($all_params, $params); - } - - // add nonce if called for - if ($add_nonce) { - if ( array_key_exists('do', $all_params) ) { - $action = $all_params['do']; - } elseif ( array_key_exists('action', $all_params) ) { - $action = $all_params['action']; - } - - $all_params['nonce'] = owa_coreAPI::createNonce($action); - } - - $get = ''; - - if (!empty($all_params)): - - $count = count($all_params); - - $i = 0; - - foreach ($all_params as $n => $v) { - - $get .= $this->config['ns'].owa_sanitize::escapeForDisplay($n).'='.owa_sanitize::escapeForDisplay($v); - - $i++; - - if ($i < $count): - $get .= "&"; - endif; - } - endif; - - if (empty($url)): - $url = $this->config['main_url']; - endif; - - $link = sprintf($this->config['link_template'], $url, $get); - - if ($xml == true): - $link = $this->escapeForXml($link); - endif; - - return $link; - - } - - function escapeForXml($string) { - - $string = str_replace(array('&', '"', "'", '<', '>' ), array('&' , '"', ''' , '<' , '>'), $string); - // removes non-ascii chars - $string = owa_lib::escapeNonAsciiChars($string); - return $string; - } - - function makeAbsoluteLink($params = array(), $add_state = false, $url = '', $xml = false) { - - if (empty($url)): - $url = $this->config['main_absolute_url']; - endif; - - return $this->makeLink($params, $add_state, $url, $xml); - - } - - function makeApiLink($params = array(), $add_state = false) { - - - $url = $this->config['api_url']; - - return $this->makeLink($params, $add_state, $url); - - } - - - function makeImageLink($path, $absolute = false) { - - if ($absolute === true) { - $url = owa_coreAPI::getSetting('base', 'modules_url'); - } else { - $url = owa_coreAPI::getSetting('base', 'modules_url'); - } - - return $url.$path; - - } - - function includeTemplate($file) { - - $this->set_template($file); - include($this->file); - return; - - } - - function setTemplate($file) { - - $this->set_template($file); - return $this->file; - - } - - function getWidget($do, $params = array(), $wrapper = true, $add_state = true) { - - $final_params = array(); - - if (empty($params)): - $params = array(); - endif; - - $params['do'] = $do; - - if ($wrapper === true): - $params['initial_view'] = true; - $params['wrapper'] = true; - elseif ($wrapper === 'inpage'): - $params['initial_view'] = true; - $params['wrapper'] = 'inpage'; - else: - $params['wrapper'] = false; - endif; - - // add state params into request params - if ($add_state === true): - $final_params = array_merge($final_params, $this->caller_params['link_state']); - endif; - - // apply overides made via the template - $final_params = array_merge($final_params, array_filter($params)); - - return owa_coreAPI::performAction($do, $final_params); - } - - function getInpageWidget($do, $params = array()) { - - return owa_template::getWidget($do, $params, 'inpage'); - - } - - function getSparkline($metric, $metric_col, $period = '', $height = 25, $width = 250, $map = array(), $add_state = true) { - - $map['metric'] = $metric; - $map['metric_col'] = $metric_col; - $map['period'] = $period; - $map['height'] = $height; - $map['width'] = $width; - return owa_template::getWidget('base.widgetSparkline', $map, false, $add_state); - - } - - function makeJson($array) { - - $reserved_words = owa_coreAPI::getSetting('base', 'reserved_words'); - - $json = '{'; - - foreach ($array as $k => $v) { - - if (is_object($v)) { - if (method_exists($v, 'toString')) { - $v = $v->toString(); - } else { - $v = ''; - } - - } - - if (in_array($k, array_keys($reserved_words))) { - $k = $reserved_words[$k]; - } - - $json .= sprintf('%s: "%s", ', $k, $v); - - } - - - $json = substr($json, 0, -2); - - $json .= '}'; - - return $json; - - } - - function headerActions() { - - return; - } - - function footerActions() { - - return; - } - - function makePagination($pagination, $map = array(), $add_state = true, $template = '') { - - $pages = ''; - //print_r($pagination); - if ($pagination['max_page_num'] > 1) { - - $pages = '
      '; - - for ($i = 1; $i <= $pagination['max_page_num'];$i++) { - - if ($pagination['page_num'] != $i) { - $new_map = array(); - $new_map = $map; - $new_map['page'] = $i; - $link = sprintf('
    • %s
    • ', - $this->makeLink($new_map, $add_state), - $i); - - } else { - - $link = sprintf('
    • %s
    • ', $i); - } - - $pages .= $link; - } - - $pages .= '
    '; - $pages .= '
    '; - } - - return $pages; - } - - function makePaginationFromResultSet($pagination, $map = array(), $add_state = true, $template = '') { - - $pages = ''; - //print_r($pagination); - //print $pagination->total_pages; - - if ($pagination->total_pages > 1) { - - $pages = '
      '; - - for ($i = 1; $i <= $pagination->total_pages;$i++) { - - if ($pagination->page != $i) { - - $new_map = array(); - - if (is_array($map)) { - $new_map = array_merge($map, $new_map); - } - - $new_map['page'] = $i; - - $link = sprintf('
    • %s
    • ', - $this->makeLink($new_map, $add_state), - $i); - - } else { - - $link = sprintf('
    • %s
    • ', $i); - } - - $pages .= $link; - } - - $pages .= '
    '; - - - - } - - return $pages; - } - - function get($name) { - - if (array_key_exists($name, $this->vars)) { - return $this->vars[$name]; - } else { - return false; - } - - } - - function getValue( $key, $var) { - - if ( isset( $var ) && is_array( $var ) ) { - if ( array_key_exists( $key, $var) ) { - return $var[$key]; - } - } - } - - function substituteValue($string, $var_name) { - - $value = $this->get($var_name); - - if ($value) { - - return sprintf($string,$value); - } - } - - function makeNavigationMenu($links, $currentSiteId) { - - if (!empty($links) && !empty($currentSiteId)) { - - $t = new owa_template; - $t->set('links', $links); - $t->set('currentSiteId', $currentSiteId); - - $t->caller_params['link_state'] = $this->caller_params['link_state']; - $t->set_template('report_nav.tpl'); - return $t->fetch(); - } else { - - return false; - } - - } - - function displayChart($id, $data, $width = '100%', $height = '200px') { - - if (!empty($data)) { - - $t = new owa_template; - $t->set('dom_id', $id.'Chart'); - $t->set('data', $data); - $t->set('width', $width); - $t->set('height', $height); - $t->set_template('chart_dom.tpl'); - return $t->fetch(); - } else { - - return false; - } - } - - function displaySparkline($id, $data, $width = '100px', $height = '35px') { - - if (!empty($data)) { - - $data_string = implode(',', $data); - - $t = new owa_template; - $t->set('dom_id', $id.'Sparkline'); - $t->set('data', $data_string); - $t->set('width', $width); - $t->set('height', $height); - $t->set_template('sparkline_dom.tpl'); - return $t->fetch(); - - } else { - - return false; - } - } - - function displaySeriesAsSparkline($name, $result_set_obj, $id = '') { - - if (!$id) { - $id = rand(); - } - - $series = $result_set_obj->getSeries($name); - - if ($series) { - echo $this->displaySparkline($id, $series); - } - } - - function makeTable($labels, $data, $table_class = '', $table_id = '', $is_sortable = true) { - - $t = new owa_template; - - if (!empty($table_id)) { - $id = rand(); - } - - $t->set('table_id', $id.'Table'); - $t->set('data', $data); - $t->set('labels', $labels); - $t->set('class', $table_class); - if ($is_sortable === true) { - $t->set('sort_table_class', 'tablesorter'); - } - - $t->set_template('generic_table.tpl'); - - return $t->fetch(); - - } - - function subTemplate($template_name = '', $map = array(), $linkstate = array()) { - - $t = new owa_template; - - $t->set_template($template_name); - - foreach ($map as $k => $v) { - - $t->set($k, $v); - } - - return $t->fetch(); - - } - - function formatNumber($num, $decimal_places) { - - return number_format($num, $decimal_places,'.',','); - } - - function getAvatarImage($email) { - - if (false != $email && $email !== '(not set)') { - $url = sprintf("https://www.gravatar.com/avatar/%s?s=30", md5($email)); - } else { - $url = $this->makeImageLink('base/i/default_user_50x50.png'); - } - - return $url; - } - - function displayMetricInfobox($params = array()) { - - $t = new owa_template; - - if (!empty($dom_id)) { - $dom_id = rand(); - } - $params['do'] = 'getResultSet'; - $count = owa_coreAPI::executeApiCommand($params); - $params['period'] = 'last_thirty_days'; - $params['dimensions'] = 'date'; - $trend = owa_coreAPI::executeApiCommand($params); - $t->set('metric_name', $params['metrics']); - $t->set('dom_id', $dom_id); - $t->set('count', $count); - $t->set('trend', $trend); - $t->set_template('metricInfobox.php'); - - return $t->fetch(); - - } - - public function renderKpiInfobox($number, $label, $link = '', $class = '') { - - $t = new owa_template; - $t->set_template( 'kpiInfobox.php' ); - $t->set( 'number', $number ); - $t->set( 'label', $label ); - - if ($link) { - $t->set( 'link', $link ); - } - - if ($class) { - $t->set( 'class', $class ); - } - - echo $t->fetch(); - - } - - function renderDimension($template, $properties) { - - $t = new owa_template; - $t->set('properties', $properties); - $t->set_template($template); - return $t->fetch(); - } - - /** - * Creates a hidden nonce form field - * - * @param string $action the action that the nonce should be tied to. - * @return string The html fragment - */ - function createNonceFormField($action) { - - return sprintf( - '', - owa_coreAPI::getSetting('base', 'ns'), - owa_coreAPI::createNonce($action)); - } - - function makeNonceLink() { - - } - - /** - * Outputs data into the template - * - * @param string $output The String to be output into the template - * @param bool $sanitize Flag that will sanitize the output for display - */ - function out($output, $sanitize = true, $decode_special_entities = false) { - - if ( $sanitize ) { - $output = owa_sanitize::escapeForDisplay($output); - - if ( $decode_special_entities ) { - $output = strtr($output, array('&' => '&')); - } - - } - - echo $output; - } - - function formatCurrency($value) { - return owa_lib::formatCurrency( $value, owa_coreAPI::getSetting( 'base', 'currencyLocal' ), owa_coreAPI::getSetting( 'base', 'currencyISO3' ) ); - } - - function getCurrentUser() { - - return owa_coreAPI::getCurrentUser(); - } - - function getLatestActions( $startDate, $endDate, $siteId, $visitorId = '', $sessionId = '', $width = '300px', $resultsPerPage = 25, $page = 1 ) { - - $la = owa_coreAPI::executeApiCommand(array( - - 'do' => 'getLatestActions', - 'siteId' => $siteId, - 'page' => $page, - 'startDate' => $startDate, - 'endDate' => $endDate, - 'visitorId' => $visitorId, - 'sessionId' => $sessionId, - 'resultsPerPage' => $resultsPerPage - )); - - - $items = $la->getResultsRows(); - - $t = new owa_template; - $t->set('items', $items); - $t->set('width', $width); - $t->set_template('widget_latestActions.php'); - return $t->fetch(); - } - - public function getSiteThumbnail( $domain, $width = '200' ) { - - echo sprintf('', urlencode($domain .'/'), $width, $width ); - } - - /** - * Checks is a display value is set. - */ - public function isValueSet( $string ) { - - if ($string === '(not set)' || empty( $string ) ) { - - return false; - - } else { - - return true; - } - } -} - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + +class owa_template extends Template { + + /** + * Configuration + * + * @var array + */ + var $config; + + var $theme_template_dir; + + var $module_local_template_dir; + + var $module_template_dir; + + var $e; + + var $period; + + /** + * Params passed by calling caller + * + * @var array + */ + var $caller_params; + + function __construct( $module = null, $caller_params = array() ) { + + $this->caller_params = $caller_params; + + $c = owa_coreAPI::configSingleton(); + $this->config = $c->fetch('base'); + + $this->e = owa_coreAPI::errorSingleton(); + + // set template dirs + if(!empty($caller_params['module'])): + $this->_setTemplateDir($module); + else: + $this->_setTemplateDir('base'); + endif; + + $this->time_now = owa_lib::time_now(); + } + + function _setTemplateDir($module) { + + // set module template dir + $this->module_template_dir = OWA_DIR.'modules'.'/' . $module . '/'.'templates'.'/'; + + // set module local template override dir + $this->module_local_template_dir = $this->module_template_dir.'local'.'/'; + + // set theme template dir + $this->theme_template_dir = OWA_THEMES_DIR.$this->config['theme'].'/'; + + return; + } + + function getTemplatePath($module, $file) { + + $this->_setTemplateDir($module); + + if ($file == null) { + owa_coreAPI::error('No template file was specified.'); + return false; + } else { + // check module's local modification template Directory + if (file_exists($this->module_local_template_dir.$file)) { + $fullfile = $this->module_local_template_dir.$file; + + // check theme's template Directory + } elseif(file_exists($this->theme_template_dir.$file)) { + $fullfile = $this->theme_template_dir.$file; + + // check module's template directory + } elseif(file_exists($this->module_template_dir.$file)) { + $fullfile = $this->module_template_dir.$file; + + // throw error + } else { + $this->e->err(sprintf('%s was not found in any template directory.', $file)); + return false; + } + return $fullfile; + } + + + + } + + /** + * Set the template file + * @depricated + * @param string $file + */ + function set_template($file = null) { + + if (!$file): + owa_coreAPI::error('No template file was specified.'); + return false; + else: + // check module's local modification template Directory + if (file_exists($this->module_local_template_dir.$file)): + $this->file = $this->module_local_template_dir.$file; + + // check theme's template Directory + elseif(file_exists($this->theme_template_dir.$file)): + $this->file = $this->theme_template_dir.$file; + + // check module's template directory + elseif(file_exists($this->module_template_dir.$file)): + $this->file = $this->module_template_dir.$file; + + // throw error + else: + $this->e->err(sprintf('%s was not found in any template directory.', $file)); + return false; + endif; + + return true; + endif; + } + + function setTemplateFile($module, $file) { + + //choose file + $filepath = $this->getTemplatePath($module, $file); + //set template + if ($filepath) { + $this->file = $filepath; + } + } + + /** + * Truncate string + * + * @param string $str + * @param integer $length + * @param string $trailing + * @return string + */ + function truncate ($str, $length=10, $trailing='...') { + + return owa_lib::truncate ($str, $length, $trailing); + } + + function get_month_label($month) { + + return owa_lib::get_month_label($month); + } + + /** + * Chooses the right icon based on browser type + * + * @param unknown_type $browser_type + * @return unknown + */ + function choose_browser_icon($browser_type, $height= '32', $width='') { + + $default_location = 'base/i/browsers/128x128/'; + + $icons = array( + + 'internet explorer' => $default_location . 'ie.png', + 'opera mini' => $default_location . 'opera.png', + 'unknown browser' => $default_location . 'default.png' + + ); + + $file = $default_location . strtolower( $browser_type ) . '.png' ; + + if ( file_exists( OWA_MODULES_DIR . $file ) ) { + + $file = $file; + + } else if ( isset( $icons[ strtolower($browser_type) ] ) ) { + + $file = $icons[ strtolower($browser_type) ]; + + } else { + + $file = $icons['unknown browser']; + } + + return sprintf( '%s', + $browser_type, + $this->makeImageLink( $file ), + $width, + $height + ); + + } + + function getBrowserIcon($browser_family, $size = '128x128', $module = 'base') { + + if ($browser_family) { + $browser_family = strtolower($browser_family); + } + + + if (file_exists(OWA_MODULES_DIR.$module.'/i/browsers/'.$size.'/'.$browser_family.'.png')) { + return $this->makeImageLink('base/i/browsers/'.$size.'/'.$browser_family.'.png'); + } else { + return $this->makeImageLink('base/i/browsers/'.$size.'/default.png'); + } + } + + + function makeLinkQueryString($query_params) { + + $new_query_params = array(); + + //Load params passed by caller + if (!empty($this->caller_params)): + foreach ($this->caller_params as $name => $value) { + if (!empty($value)): + $new_query_params[$name] = $value; + endif; + } + endif; + + // Load overrides + if (!empty($query_params)): + foreach ($query_params as $name => $value) { + if (!empty($value)): + $new_query_params[$name] = $value; + endif; + } + endif; + + // Construct GET request + if (!empty($new_query_params)): + foreach ($new_query_params as $name => $value) { + if (!empty($value)): + $get .= $name . "=" . $value . "&"; + endif; + } + endif; + + return $get; + + } + + /** + * Makes navigation links by checking whether or not the view + * that is rendering the template is not the view being refered to in the link. + * + * @param array navigation array + */ + function makeNavigation($nav, $id = '', $class = '', $li_template = '
  • %s
  • ', $li_class = '') { + + $ul = sprintf('
      ', $id, $class); + + if (!empty($nav)): + + $navigation = $ul; + + foreach($nav as $k => $v) { + + $navigation .= sprintf($li_template, $li_class, $this->makeLink(array('do' => $v['ref']), true), $v['anchortext']); + + } + + $navigation .= '
    '; + + return $navigation; + else: + return false; + endif; + + } + + function makeTwoLevelNav($links) { + print_r($links); + $navigation = '
      '; + + foreach($links as $k => $v) { + + if (!empty($v['subgroup'])): + $sub_nav = $this->makeNavigation($v['subgroup']); + + $navigation .= sprintf('
    • %s
    • ', + $this->makeLink(array('do' => $v['ref']), true), + $v['anchortext'], $sub_nav); + else: + + $navigation .= sprintf('
    • ', + $this->makeLink(array('do' => $v['ref']), true), + $v['anchortext']); + + endif; + + } + + $navigation .= '
    '; + + return $navigation; + + } + + function daysAgo($time) { + + $now = mktime(23, 59, 59, $this->time_now['month'], $this->time_now['day'], $this->time_now['year']); + + $days = round(($now - $time) / (3600*24)); + + switch ($days) { + + case 1: + return $days . " day ago"; + + default: + return $days . " days ago"; + } + + } + + /** + * @depricated + * @todo remove + */ + function getAuthStatus() { + + if (!class_exists('owa_auth')) { + require_once(OWA_BASE_DIR.'/owa_auth.php'); + } + + $auth = &owa_auth::get_instance(); + return $auth->auth_status; + } + + function makeWikiLink($page) { + + return sprintf($this->config['owa_wiki_link_template'], $page); + } + + /** + * Returns Namespace value to template + * + * @return string + */ + function getNs() { + + return $this->config['ns']; + } + + function makeParamString($params = array(), $add_state = false, $format = 'query', $namespace = true) { + + $all_params = array(); + + // merge in state params + if ($add_state) { + $all_params = array_merge($all_params, $this->getAllStateParams()); + } + //merge in params + $all_params = array_merge($all_params, $params); + + switch($format) { + + case 'query': + + $get = ''; + + $count = count($all_params); + + $i = 0; + + foreach ($all_params as $n => $v) { + + $get .= owa_coreAPI::getSetting('base','ns').$n.'='.$v; + + $i++; + + if ($i < $count): + $get .= "&"; + endif; + } + + $string= $get; + + break; + + case 'cookie': + + $string = owa_lib::implode_assoc('=>', '|||', $all_params); + break; + + case 'json': + + $string = json_encode( $all_params ); + + break; + } + + + return $string; + + } + + function getAllStateParams() { + + $all_params = array(); + + if (!empty($this->caller_params['link_state'])) { + $all_params = array_merge($all_params, $this->caller_params['link_state']); + } + + // add in period properties if available + $period = $this->get('timePeriod'); + + if (!empty($period)) { + $all_params = array_merge($all_params, $period->getPeriodProperties()); + //print_r($all_params); + } + + return $all_params; + } + + + /** + * Makes Links, adds state to links optionaly. + * + * @param array $params + * @param boolean $add_state + * @return string + */ + function makeLink($params = array(), $add_state = false, $url = '', $xml = false, $add_nonce = false) { + + $all_params = array(); + + //Loads link state passed by caller + if ($add_state == true) { + if (!empty($this->caller_params['link_state'])) { + $all_params = array_merge($all_params, $this->caller_params['link_state']); + } + + // add in period properties if available + $period = $this->get('timePeriod'); + + if (!empty($period)) { + $all_params = array_merge($all_params, $period->getPeriodProperties()); + + } + } + + // Load overrides + if (!empty($params)) { + $params = array_filter($params); + $all_params = array_merge($all_params, $params); + } + + // add nonce if called for + if ($add_nonce) { + if ( array_key_exists('do', $all_params) ) { + $action = $all_params['do']; + } elseif ( array_key_exists('action', $all_params) ) { + $action = $all_params['action']; + } + + $all_params['nonce'] = owa_coreAPI::createNonce($action); + } + + $get = ''; + + if (!empty($all_params)): + + $count = count($all_params); + + $i = 0; + + foreach ($all_params as $n => $v) { + + $get .= $this->config['ns'].owa_sanitize::escapeForDisplay($n).'='.owa_sanitize::escapeForDisplay($v); + + $i++; + + if ($i < $count): + $get .= "&"; + endif; + } + endif; + + if (empty($url)): + $url = $this->config['main_url']; + endif; + + $link = sprintf($this->config['link_template'], $url, $get); + + if ($xml == true): + $link = $this->escapeForXml($link); + endif; + + return $link; + + } + + function escapeForXml($string) { + + $string = str_replace(array('&', '"', "'", '<', '>' ), array('&' , '"', ''' , '<' , '>'), $string); + // removes non-ascii chars + $string = owa_lib::escapeNonAsciiChars($string); + return $string; + } + + function makeAbsoluteLink($params = array(), $add_state = false, $url = '', $xml = false) { + + if (empty($url)): + $url = $this->config['main_absolute_url']; + endif; + + return $this->makeLink($params, $add_state, $url, $xml); + + } + + function makeApiLink($params = array(), $add_state = false) { + + + $url = $this->config['api_url']; + + return $this->makeLink($params, $add_state, $url); + + } + + + function makeImageLink($path, $absolute = false) { + + if ($absolute === true) { + $url = owa_coreAPI::getSetting('base', 'modules_url'); + } else { + $url = owa_coreAPI::getSetting('base', 'modules_url'); + } + + return $url.$path; + + } + + function includeTemplate($file) { + + $this->set_template($file); + include($this->file); + return; + + } + + function setTemplate($file) { + + $this->set_template($file); + return $this->file; + + } + + function getWidget($do, $params = array(), $wrapper = true, $add_state = true) { + + $final_params = array(); + + if (empty($params)): + $params = array(); + endif; + + $params['do'] = $do; + + if ($wrapper === true): + $params['initial_view'] = true; + $params['wrapper'] = true; + elseif ($wrapper === 'inpage'): + $params['initial_view'] = true; + $params['wrapper'] = 'inpage'; + else: + $params['wrapper'] = false; + endif; + + // add state params into request params + if ($add_state === true): + $final_params = array_merge($final_params, $this->caller_params['link_state']); + endif; + + // apply overides made via the template + $final_params = array_merge($final_params, array_filter($params)); + + return owa_coreAPI::performAction($do, $final_params); + } + + function getInpageWidget($do, $params = array()) { + + return owa_template::getWidget($do, $params, 'inpage'); + + } + + function getSparkline($metric, $metric_col, $period = '', $height = 25, $width = 250, $map = array(), $add_state = true) { + + $map['metric'] = $metric; + $map['metric_col'] = $metric_col; + $map['period'] = $period; + $map['height'] = $height; + $map['width'] = $width; + return owa_template::getWidget('base.widgetSparkline', $map, false, $add_state); + + } + + function makeJson($array) { + + $reserved_words = owa_coreAPI::getSetting('base', 'reserved_words'); + + $json = '{'; + + foreach ($array as $k => $v) { + + if (is_object($v)) { + if (method_exists($v, 'toString')) { + $v = $v->toString(); + } else { + $v = ''; + } + + } + + if (in_array($k, array_keys($reserved_words))) { + $k = $reserved_words[$k]; + } + + $json .= sprintf('%s: "%s", ', $k, $v); + + } + + + $json = substr($json, 0, -2); + + $json .= '}'; + + return $json; + + } + + function headerActions() { + + return; + } + + function footerActions() { + + return; + } + + function makePagination($pagination, $map = array(), $add_state = true, $template = '') { + + $pages = ''; + //print_r($pagination); + if ($pagination['max_page_num'] > 1) { + + $pages = '
      '; + + for ($i = 1; $i <= $pagination['max_page_num'];$i++) { + + if ($pagination['page_num'] != $i) { + $new_map = array(); + $new_map = $map; + $new_map['page'] = $i; + $link = sprintf('
    • %s
    • ', + $this->makeLink($new_map, $add_state), + $i); + + } else { + + $link = sprintf('
    • %s
    • ', $i); + } + + $pages .= $link; + } + + $pages .= '
    '; + $pages .= '
    '; + } + + return $pages; + } + + function makePaginationFromResultSet($pagination, $map = array(), $add_state = true, $template = '') { + + $pages = ''; + //print_r($pagination); + //print $pagination->total_pages; + + if ($pagination->total_pages > 1) { + + $pages = '
      '; + + for ($i = 1; $i <= $pagination->total_pages;$i++) { + + if ($pagination->page != $i) { + + $new_map = array(); + + if (is_array($map)) { + $new_map = array_merge($map, $new_map); + } + + $new_map['page'] = $i; + + $link = sprintf('
    • %s
    • ', + $this->makeLink($new_map, $add_state), + $i); + + } else { + + $link = sprintf('
    • %s
    • ', $i); + } + + $pages .= $link; + } + + $pages .= '
    '; + + + + } + + return $pages; + } + + function get($name) { + + if (array_key_exists($name, $this->vars)) { + return $this->vars[$name]; + } else { + return false; + } + + } + + function getValue( $key, $var) { + + if ( isset( $var ) && is_array( $var ) ) { + if ( array_key_exists( $key, $var) ) { + return $var[$key]; + } + } + } + + function substituteValue($string, $var_name) { + + $value = $this->get($var_name); + + if ($value) { + + return sprintf($string,$value); + } + } + + function makeNavigationMenu($links, $currentSiteId) { + + if (!empty($links) && !empty($currentSiteId)) { + + $t = new owa_template; + $t->set('links', $links); + $t->set('currentSiteId', $currentSiteId); + + $t->caller_params['link_state'] = $this->caller_params['link_state']; + $t->set_template('report_nav.tpl'); + return $t->fetch(); + } else { + + return false; + } + + } + + function displayChart($id, $data, $width = '100%', $height = '200px') { + + if (!empty($data)) { + + $t = new owa_template; + $t->set('dom_id', $id.'Chart'); + $t->set('data', $data); + $t->set('width', $width); + $t->set('height', $height); + $t->set_template('chart_dom.tpl'); + return $t->fetch(); + } else { + + return false; + } + } + + function displaySparkline($id, $data, $width = '100px', $height = '35px') { + + if (!empty($data)) { + + $data_string = implode(',', $data); + + $t = new owa_template; + $t->set('dom_id', $id.'Sparkline'); + $t->set('data', $data_string); + $t->set('width', $width); + $t->set('height', $height); + $t->set_template('sparkline_dom.tpl'); + return $t->fetch(); + + } else { + + return false; + } + } + + function displaySeriesAsSparkline($name, $result_set_obj, $id = '') { + + if (!$id) { + $id = rand(); + } + + $series = $result_set_obj->getSeries($name); + + if ($series) { + echo $this->displaySparkline($id, $series); + } + } + + function makeTable($labels, $data, $table_class = '', $table_id = '', $is_sortable = true) { + + $t = new owa_template; + + if (!empty($table_id)) { + $id = rand(); + } + + $t->set('table_id', $id.'Table'); + $t->set('data', $data); + $t->set('labels', $labels); + $t->set('class', $table_class); + if ($is_sortable === true) { + $t->set('sort_table_class', 'tablesorter'); + } + + $t->set_template('generic_table.tpl'); + + return $t->fetch(); + + } + + function subTemplate($template_name = '', $map = array(), $linkstate = array()) { + + $t = new owa_template; + + $t->set_template($template_name); + + foreach ($map as $k => $v) { + + $t->set($k, $v); + } + + return $t->fetch(); + + } + + function formatNumber($num, $decimal_places) { + + return number_format($num, $decimal_places,'.',','); + } + + function getAvatarImage($email) { + + if (false != $email && $email !== '(not set)') { + $url = sprintf("https://www.gravatar.com/avatar/%s?s=30", md5($email)); + } else { + $url = $this->makeImageLink('base/i/default_user_50x50.png'); + } + + return $url; + } + + function displayMetricInfobox($params = array()) { + + $t = new owa_template; + + if (!empty($dom_id)) { + $dom_id = rand(); + } + $params['do'] = 'getResultSet'; + $count = owa_coreAPI::executeApiCommand($params); + $params['period'] = 'last_thirty_days'; + $params['dimensions'] = 'date'; + $trend = owa_coreAPI::executeApiCommand($params); + $t->set('metric_name', $params['metrics']); + $t->set('dom_id', $dom_id); + $t->set('count', $count); + $t->set('trend', $trend); + $t->set_template('metricInfobox.php'); + + return $t->fetch(); + + } + + public function renderKpiInfobox($number, $label, $link = '', $class = '') { + + $t = new owa_template; + $t->set_template( 'kpiInfobox.php' ); + $t->set( 'number', $number ); + $t->set( 'label', $label ); + + if ($link) { + $t->set( 'link', $link ); + } + + if ($class) { + $t->set( 'class', $class ); + } + + echo $t->fetch(); + + } + + function renderDimension($template, $properties) { + + $t = new owa_template; + $t->set('properties', $properties); + $t->set_template($template); + return $t->fetch(); + } + + /** + * Creates a hidden nonce form field + * + * @param string $action the action that the nonce should be tied to. + * @return string The html fragment + */ + function createNonceFormField($action) { + + return sprintf( + '', + owa_coreAPI::getSetting('base', 'ns'), + owa_coreAPI::createNonce($action)); + } + + function makeNonceLink() { + + } + + /** + * Outputs data into the template + * + * @param string $output The String to be output into the template + * @param bool $sanitize Flag that will sanitize the output for display + */ + function out($output, $sanitize = true, $decode_special_entities = false) { + + if ( $sanitize ) { + $output = owa_sanitize::escapeForDisplay($output); + + if ( $decode_special_entities ) { + $output = strtr($output, array('&' => '&')); + } + + } + + echo $output; + } + + function formatCurrency($value) { + return owa_lib::formatCurrency( $value, owa_coreAPI::getSetting( 'base', 'currencyLocal' ), owa_coreAPI::getSetting( 'base', 'currencyISO3' ) ); + } + + function getCurrentUser() { + + return owa_coreAPI::getCurrentUser(); + } + + function getLatestActions( $startDate, $endDate, $siteId, $visitorId = '', $sessionId = '', $width = '300px', $resultsPerPage = 25, $page = 1 ) { + + $la = owa_coreAPI::executeApiCommand(array( + + 'do' => 'getLatestActions', + 'siteId' => $siteId, + 'page' => $page, + 'startDate' => $startDate, + 'endDate' => $endDate, + 'visitorId' => $visitorId, + 'sessionId' => $sessionId, + 'resultsPerPage' => $resultsPerPage + )); + + + $items = $la->getResultsRows(); + + $t = new owa_template; + $t->set('items', $items); + $t->set('width', $width); + $t->set_template('widget_latestActions.php'); + return $t->fetch(); + } + + public function getSiteThumbnail( $domain, $width = '200' ) { + + echo sprintf('', urlencode($domain .'/'), $width, $width ); + } + + /** + * Checks is a display value is set. + */ + public function isValueSet( $string ) { + + if ($string === '(not set)' || empty( $string ) ) { + + return false; + + } else { + + return true; + } + } +} + + ?> \ No newline at end of file diff --git a/owa_view.php b/owa_view.php index 1a41e8695..0e33e142f 100644 --- a/owa_view.php +++ b/owa_view.php @@ -27,517 +27,517 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_view extends owa_base { - /** - * Main view template object - * - * @var object - */ - var $t; - - /** - * Body content template object - * - * @var object - */ - var $body; - - /** - * Sub View object - * - * @var object - */ - var $subview; - - /** - * Rednered subview - * - * @var string - */ - var $subview_rendered; - - /** - * CSS file for main template - * - * @var unknown_type - */ - var $css_file; - - /** - * The priviledge level required to access this view - * @depricated - * @var string - */ - var $priviledge_level; - - /** - * Type of page - * - * @var unknown_type - */ - var $page_type; - - /** - * Request Params - * - * @var unknown_type - */ - var $params; - - /** - * Authorization object - * - * @var object - */ - var $auth; - - var $module; // set by factory. - - var $data; - - var $default_subview; - - var $is_subview; - - var $js = array(); - - var $css = array(); - - var $postProcessView = false; - - var $renderJsInline; - - /** - * Constructor - * - */ - function __construct($params = null) { - - parent::__construct($params); - - $this->t = new owa_template(); - $this->body = new owa_template($this->module); - $this->setTheme(); - $this->setCss("base/css/owa.css"); - } - - /** - * Assembles the view using passed model objects - * - * @param unknown_type $data - * @return unknown - */ - function assembleView($data) { - - $this->e->debug('Assembling view: '.get_class($this)); - - - // set view name in template class. used for navigation. - if (array_key_exists('view', $this->data)) { - $this->body->caller_params['view'] = $this->data['view']; - } - - if (array_key_exists('params', $this->data)): - $this->body->set('params', $this->data['params']); - endif; - - if (array_key_exists('subview', $this->data)): - $this->body->caller_params['subview'] = $this->data['subview']; - endif; - - // Assign status msg - if (array_key_exists('status_msg', $this->data)): - $this->t->set('status_msg', $this->data['status_msg']); - endif; - - // get status msg from code passed on the query string from a redirect. - if (array_key_exists('status_code', $this->data)): - $this->t->set('status_msg', $this->getMsg($this->data['status_code'])); - endif; - - // set error msg directly if passed from constructor - if (array_key_exists('error_msg', $this->data)): - $this->t->set('error_msg', $this->data['error_msg']); - endif; - - // authentication status - if (array_key_exists('auth_status', $this->data)): - $this->t->set('authStatus', $this->data['auth_status']); - endif; - - // get error msg from error code passed on the query string from a redirect. - if (array_key_exists('error_code', $this->data)): - $this->t->set('error_msg', $this->getMsg($this->data['error_code'])); - endif; - - // load subview - if (!empty($this->data['subview']) || !empty($this->default_subview)): - // Load subview - $this->loadSubView($this->data['subview']); - endif; - - // construct main view. This might set some properties of the subview. - if (method_exists($this, 'render')) { - $this->render($this->data); - } else { - // old style - $this->construct($this->data); - } - //array of errors usually used for field validations - if (array_key_exists('validation_errors', $this->data)): - $this->body->set('validation_errors', $this->data['validation_errors']); - endif; - - // pagination - if (array_key_exists('pagination', $this->data)): - $this->body->set('pagination', $this->data['pagination']); - endif; - - //$this->_setLinkState(); - - // assemble subview - if (!empty($this->data['subview'])): - - // set view name in template. used for navigation. - $this->subview->body->caller_params['view'] = $this->data['subview']; - - // Set validation errors - $this->subview->body->set('validation_errors', $this->get('validation_errors')); - - // pagination - if (array_key_exists('pagination', $this->data)): - $this->subview->body->set('pagination', $this->data['pagination']); - endif; - - if (array_key_exists('params', $this->data)): - $this->subview->body->set('params', $this->data['params']); - $this->subview->body->set('do', $this->data['params']['do']); - endif; - - // Load subview - $this->renderSubView($this->data); - - // assign subview to body template - $this->body->set('subview', $this->subview_rendered); - - - endif; - - // assign validation errors - if (!empty($this->data['validation_errors'])) { - $this->t->set('validation_errors', $this->data['validation_errors']); - } - - - // fire post method - $this->post(); - - // assign css and js ellements if the view is not a subview. - // subview css/js have been merged/pulls from subview and assigned here. - if ($this->is_subview != true) { - if (!empty($this->css)) { - $this->t->set('css', $this->css); - } - - if (!empty($this->js)) { - $this->t->set('js', $this->js); - } - } - - //Assign body to main template - $this->t->set('config', $this->config); - - //Assign body to main template - $this->t->set('body', $this->body); - - if ($this->postProcessView === true){ - return $this->postProcess(); - } else { - // Return fully asembled View - return $this->t->fetch(); - } - } - - /** - * Abstract Alternative rendering method reuires the setting of $this->postProcessView to fire - * - */ - function postProcess() { - - return false; - } - - /** - * Post method fired right before view is rendered and returned - * as output - */ - function post() { - - return false; - } - - - /** - * Sets the theme to be used by a view - * - */ - function setTheme() { - - $this->t->set_template($this->config['report_wrapper']); - - return; - } - - /** - * Abstract method for assembling a view - * @depricated - * @param array $data - */ - function construct($data) { - - return; - - } - - /** - * Assembles subview - * - * @param array $data - */ - function loadSubView($subview) { - - if (empty($subview)): - if (!empty($this->default_subview)): - $subview = $this->default_subview; - $this->data['subview'] = $this->default_subview; - else: - return $this->e->debug("No Subview was specified by caller."); - endif; - endif; - - $this->subview = owa_coreAPI::subViewFactory($subview); - //print_r($subview.'///'); - $this->subview->setData($this->data); - } - - /** - * Assembles subview - * - * @param array $data - */ - function renderSubView($data) { - - // Stores subview as string into $this->subview - $this->subview_rendered = $this->subview->assembleSubView($data); - - // pull css and js elements needed by subview - $this->css = array_merge($this->css, $this->subview->css); - $this->js = array_merge($this->js, $this->subview->js); - } - - /** - * Assembles the view using passed model objects - * - * @param unknown_type $data - * @return unknown - */ - function assembleSubView($data) { - - // construct main view. This might set some properties of the subview. - if (method_exists($this, 'render')) { - $this->render($data); - } else { - // old style - $this->construct($data); - } - - $this->t->set_template('wrapper_subview.tpl'); - - //Assign body to main template - $this->t->set('body', $this->body); - - // Return fully asembled View - $page = $this->t->fetch(); - - return $page; - - } - - function setCss($path, $version = null, $deps = array(), $ie_only = false) { - - if ( ! $version ) { - $version = OWA_VERSION; - } - - $uid = $path; - $url = sprintf('%s?version=%s', owa_coreAPI::getSetting('base', 'modules_url').$path, $version); - $this->css[$uid]['url'] = $url; - // build file system path just in case we need to concatenate the JS into a single file. - $fs_path = OWA_MODULES_DIR.$path; - $this->css[$uid]['path'] = $fs_path; - $this->css[$uid]['deps'] = $deps; - $this->css[$uid]['version'] = $version; - $this->css[$uid]['ie_only'] = $ie_only; - } - - function setJs($name, $path, $version ='', $deps = array(), $ie_only = false) { - - if (empty($version)) { - $version = OWA_VERSION; - } - - $uid = $name.$version; - - $url = sprintf('%s?version=%s', owa_coreAPI::getSetting('base', 'modules_url').$path, $version); - $this->js[$uid]['url'] = $url; - - // build file system path just in case we need to concatenate the JS into a single file. - $fs_path = OWA_MODULES_DIR.$path; - $this->js[$uid]['path'] = $fs_path; - $this->js[$uid]['deps'] = $deps; - $this->js[$uid]['version'] = $version; - $this->js[$uid]['ie_only'] = $ie_only; - } - - function concatinateJs() { - - $js_libs = ''; - - foreach ($this->js as $lib) { - - $js_libs .= file_get_contents($lib['path']); - $js_libs .= "\n\n"; - } - - $this->body->set('js_includes', $js_libs); - - return; - - } - - /** - * Sets flag to tell view to render the JS inline as -END_OF_SCRIPT; - $this->_opened = true; - } - - return $this->_opened; - } - - /** - * Closes the output stream if it is open. If there are still pending - * lines in the output buffer, the output window will be opened so that - * the buffer can be drained. - * - * @access public - */ - function close() - { - /* - * If there are still lines waiting to be written, open the output - * window so that we can drain the buffer. - */ - if (!$this->_opened && (count($this->_buffer) > 0)) { - $this->open(); - } - - if ($this->_opened) { - $this->_writeln(''); - $this->_writeln(''); - $this->_opened = false; - } - - return ($this->_opened === false); - } - - /** - * Writes a single line of text to the output window. - * - * @param string $line The line of text to write. - * - * @access private - */ - function _writeln($line) - { - /* Add this line to our output buffer. */ - $this->_buffer[] = $line; - - /* Buffer the output until this page's headers have been sent. */ - if (!headers_sent()) { - // return; - } - - /* If we haven't already opened the output window, do so now. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Drain the buffer to the output window. */ - $win = $this->_name; - foreach ($this->_buffer as $line) { - $this->debug .= "\n"; - } - - /* Now that the buffer has been drained, clear it. */ - $this->_buffer = array(); - } - - /** - * Logs $message to the output window. The message is also passed along - * to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - list($usec, $sec) = explode(' ', microtime()); - - /* Build the output line that contains the log entry row. */ - $line = ''; - $line .= sprintf('%s.%s', - strftime('%T', $sec), substr($usec, 2, 2)); - if (!empty($this->_ident)) { - $line .= '' . $this->_ident . ''; - } - $line .= '' . ucfirst($this->priorityToString($priority)) . ''; - $line .= sprintf('%s', - $this->_colors[$priority], - preg_replace('/\r\n|\n|\r/', '
    ', $message)); - $line .= ''; - - $this->_writeln($line); - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - -} + + * @since OWA 1.0.0 + * @package OWA + * + * @example winstatic.php Using the window handler. + */ +class Log_winstatic extends Log { + + + /** + * The name of the output window. + * @var string + * @access private + */ + var $_name = 'LogWindow'; + + /** + * The title of the output window. + * @var string + * @access private + */ + var $_title = 'Log Output Window'; + + /** + * Mapping of log priorities to colors. + * @var array + * @access private + */ + var $_colors = array( + PEAR_LOG_EMERG => 'red', + PEAR_LOG_ALERT => 'orange', + PEAR_LOG_CRIT => 'yellow', + PEAR_LOG_ERR => 'green', + PEAR_LOG_WARNING => 'blue', + PEAR_LOG_NOTICE => 'indigo', + PEAR_LOG_INFO => 'violet', + PEAR_LOG_DEBUG => 'black' + ); + + /** + * String buffer that holds line that are pending output. + * @var array + * @access private + */ + var $_buffer = array(); + + /** + * Constructs a new Log_win object. + * + * @param string $name Ignored. + * @param string $ident The identity string. + * @param array $conf The configuration array. + * @param int $level Log messages up to and including this level. + * @access public + */ + function __construct($name, $ident = '', $conf = array(), + $level = PEAR_LOG_DEBUG) + { + + $this->_id = md5(microtime()); + $this->_name = $name; + $this->_ident = $ident; + $this->_mask = Log::UPTO($level); + + // fetches the static array that will store output to be printed later + $this->debug = &owa_error::get_msgs(); + + if (isset($conf['title'])) { + $this->_title = $conf['title']; + } + if (isset($conf['colors']) && is_array($conf['colors'])) { + $this->_colors = $conf['colors']; + } + + register_shutdown_function(array(&$this, '_Log_winstatic')); + } + + /** + * Destructor + */ + function _Log_winstatic() + { + if ($this->_opened || (count($this->_buffer) > 0)) { + $this->close(); + } + } + + /** + * The first time open() is called, it will open a new browser window and + * prepare it for output. + * + * This is implicitly called by log(), if necessary. + * + * @access public + */ + function open() + { + if (!$this->_opened) { + $win = $this->_name; + + if (!empty($this->_ident)) { + $identHeader = "$win.document.writeln('Ident')"; + } else { + $identHeader = ''; + } + + $this->debug .= <<< END_OF_SCRIPT + +END_OF_SCRIPT; + $this->_opened = true; + } + + return $this->_opened; + } + + /** + * Closes the output stream if it is open. If there are still pending + * lines in the output buffer, the output window will be opened so that + * the buffer can be drained. + * + * @access public + */ + function close() + { + /* + * If there are still lines waiting to be written, open the output + * window so that we can drain the buffer. + */ + if (!$this->_opened && (count($this->_buffer) > 0)) { + $this->open(); + } + + if ($this->_opened) { + $this->_writeln(''); + $this->_writeln(''); + $this->_opened = false; + } + + return ($this->_opened === false); + } + + /** + * Writes a single line of text to the output window. + * + * @param string $line The line of text to write. + * + * @access private + */ + function _writeln($line) + { + /* Add this line to our output buffer. */ + $this->_buffer[] = $line; + + /* Buffer the output until this page's headers have been sent. */ + if (!headers_sent()) { + // return; + } + + /* If we haven't already opened the output window, do so now. */ + if (!$this->_opened && !$this->open()) { + return false; + } + + /* Drain the buffer to the output window. */ + $win = $this->_name; + foreach ($this->_buffer as $line) { + $this->debug .= "\n"; + } + + /* Now that the buffer has been drained, clear it. */ + $this->_buffer = array(); + } + + /** + * Logs $message to the output window. The message is also passed along + * to any Log_observer instances that are observing this Log. + * + * @param mixed $message String or object containing the message to log. + * @param string $priority The priority of the message. Valid + * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, + * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, + * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. + * @return boolean True on success or false on failure. + * @access public + */ + function log($message, $priority = null) + { + /* If a priority hasn't been specified, use the default value. */ + if ($priority === null) { + $priority = $this->_priority; + } + + /* Abort early if the priority is above the maximum logging level. */ + if (!$this->_isMasked($priority)) { + return false; + } + + /* Extract the string representation of the message. */ + $message = $this->_extractMessage($message); + + list($usec, $sec) = explode(' ', microtime()); + + /* Build the output line that contains the log entry row. */ + $line = ''; + $line .= sprintf('%s.%s', + strftime('%T', $sec), substr($usec, 2, 2)); + if (!empty($this->_ident)) { + $line .= '' . $this->_ident . ''; + } + $line .= '' . ucfirst($this->priorityToString($priority)) . ''; + $line .= sprintf('%s', + $this->_colors[$priority], + preg_replace('/\r\n|\n|\r/', '
    ', $message)); + $line .= ''; + + $this->_writeln($line); + + $this->_announce(array('priority' => $priority, 'message' => $message)); + + return true; + } + +} ?> \ No newline at end of file diff --git a/plugins/validations/emailAddress.php b/plugins/validations/emailAddress.php index a320d8e19..0f17cc949 100644 --- a/plugins/validations/emailAddress.php +++ b/plugins/validations/emailAddress.php @@ -24,32 +24,32 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_emailAddressValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $this->setErrorMessage('The email address is not valid.'); - } + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $this->setErrorMessage('The email address is not valid.'); + } - $email = $this->getValues(); - - if ( ! filter_var ( $email, FILTER_VALIDATE_EMAIL ) ) { - - $this->hasError(); - } - } + $email = $this->getValues(); + + if ( ! filter_var ( $email, FILTER_VALIDATE_EMAIL ) ) { + + $this->hasError(); + } + } } ?> \ No newline at end of file diff --git a/plugins/validations/entityDoesNotExist.php b/plugins/validations/entityDoesNotExist.php index a4dcd629d..aea49c9c0 100644 --- a/plugins/validations/entityDoesNotExist.php +++ b/plugins/validations/entityDoesNotExist.php @@ -1,64 +1,64 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_entityDoesNotExistValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - - function validate() { - - $entity = owa_coreAPI::entityFactory($this->getConfig('entity')); - $entity->getByColumn($this->getConfig('column'), $this->getValues()); - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $this->setErrorMessage('An entity with that value already exists.'); - } - - $id = $entity->get('id'); - - // validation logic - if (!empty($id)) { - $this->hasError(); - } - - return; - - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_entityDoesNotExistValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + + function validate() { + + $entity = owa_coreAPI::entityFactory($this->getConfig('entity')); + $entity->getByColumn($this->getConfig('column'), $this->getValues()); + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $this->setErrorMessage('An entity with that value already exists.'); + } + + $id = $entity->get('id'); + + // validation logic + if (!empty($id)) { + $this->hasError(); + } + + return; + + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/entityExists.php b/plugins/validations/entityExists.php index 95e735a13..6a6ffa655 100644 --- a/plugins/validations/entityExists.php +++ b/plugins/validations/entityExists.php @@ -1,63 +1,63 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_entityExistsValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $entity = owa_coreAPI::entityFactory($this->getConfig('entity')); - $entity->getByColumn($this->getConfig('column'), $this->getValues()); - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $this->setErrorMessage('An entity with that value does not exist.'); - } - - $id = $entity->get('id'); - - // validation logic - if (empty($id)) { - $this->hasError(); - } - - return; - - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_entityExistsValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $entity = owa_coreAPI::entityFactory($this->getConfig('entity')); + $entity->getByColumn($this->getConfig('column'), $this->getValues()); + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $this->setErrorMessage('An entity with that value does not exist.'); + } + + $id = $entity->get('id'); + + // validation logic + if (empty($id)) { + $this->hasError(); + } + + return; + + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/required.php b/plugins/validations/required.php index cd8a9ef9b..745492de9 100644 --- a/plugins/validations/required.php +++ b/plugins/validations/required.php @@ -1,58 +1,58 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_requiredValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $value = $this->getValues(); - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $this->setErrorMessage('Required field was empty.'); - } - - if (empty($value)): - $this->hasError(); - endif; - - return; - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_requiredValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $value = $this->getValues(); + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $this->setErrorMessage('Required field was empty.'); + } + + if (empty($value)): + $this->hasError(); + endif; + + return; + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/stringLength.php b/plugins/validations/stringLength.php index d48f012cd..227a54269 100644 --- a/plugins/validations/stringLength.php +++ b/plugins/validations/stringLength.php @@ -1,86 +1,86 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_stringLengthValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $value = $this->getValues(); - $length = $this->getConfig('length'); - $operator = $this->getConfig('operator'); - - // default error msg - $errorMsg = $this->getErrorMsg(); - if (empty($errorMsg)) { - - $this->setErrorMessage(sprintf("Must be %s %d character in length.", $operator, $length)); - } - - switch ($operator) { - - case '<': - if (strlen($value) >= $length) { - $this->hasError(); - } - break; - - case '>': - if (strlen($value) <= $length) { - $this->hasError(); - } - break; - - case '<=': - if (strlen($value) > $length) { - $this->hasError(); - } - break; - - case '>=': - if (strlen($value) < $length) { - $this->hasError(); - } - break; - - } - - return; - - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_stringLengthValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $value = $this->getValues(); + $length = $this->getConfig('length'); + $operator = $this->getConfig('operator'); + + // default error msg + $errorMsg = $this->getErrorMsg(); + if (empty($errorMsg)) { + + $this->setErrorMessage(sprintf("Must be %s %d character in length.", $operator, $length)); + } + + switch ($operator) { + + case '<': + if (strlen($value) >= $length) { + $this->hasError(); + } + break; + + case '>': + if (strlen($value) <= $length) { + $this->hasError(); + } + break; + + case '<=': + if (strlen($value) > $length) { + $this->hasError(); + } + break; + + case '>=': + if (strlen($value) < $length) { + $this->hasError(); + } + break; + + } + + return; + + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/stringMatch.php b/plugins/validations/stringMatch.php index 406f8a033..66833ad68 100644 --- a/plugins/validations/stringMatch.php +++ b/plugins/validations/stringMatch.php @@ -1,65 +1,65 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_stringMatchValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - - function validate() { - - $values_array = $this->getValues(); - $string1 = $values_array[0]; - $string2 = $values_array[1]; - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $this->setErrorMessage('Strings do not match.'); - } - - // validation logic - if ($string1 === $string2) { - ; - } else { - $this->hasError(); - } - - return; - - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_stringMatchValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + + function validate() { + + $values_array = $this->getValues(); + $string1 = $values_array[0]; + $string2 = $values_array[1]; + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $this->setErrorMessage('Strings do not match.'); + } + + // validation logic + if ($string1 === $string2) { + ; + } else { + $this->hasError(); + } + + return; + + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/subStringMatch.php b/plugins/validations/subStringMatch.php index 9bb87841f..15c5d810b 100644 --- a/plugins/validations/subStringMatch.php +++ b/plugins/validations/subStringMatch.php @@ -1,74 +1,74 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_subStringMatchValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $value = $this->getValues(); - $length = strlen($this->getConfig('match')); - $str = substr($value, $this->getConfig('position'), $length); - - switch ($this->getConfig('operator')) { - - case "=": - - if ($str != $this->getConfig('match')) { - $this->hasError(); - //print $str; - } - - break; - - case "!=": - - if ($str === $this->getConfig('match')) { - $this->hasError(); - } - - break; - } - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $error = $this->setErrorMessage(sprintf('The string "%s" was found within the value at position %d', $this->getConfig('match'), $this->getConfig('position'))); - } - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_subStringMatchValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $value = $this->getValues(); + $length = strlen($this->getConfig('match')); + $str = substr($value, $this->getConfig('position'), $length); + + switch ($this->getConfig('operator')) { + + case "=": + + if ($str != $this->getConfig('match')) { + $this->hasError(); + //print $str; + } + + break; + + case "!=": + + if ($str === $this->getConfig('match')) { + $this->hasError(); + } + + break; + } + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $error = $this->setErrorMessage(sprintf('The string "%s" was found within the value at position %d', $this->getConfig('match'), $this->getConfig('position'))); + } + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/subStringPosition.php b/plugins/validations/subStringPosition.php index ddb51eae7..e3c8d572a 100644 --- a/plugins/validations/subStringPosition.php +++ b/plugins/validations/subStringPosition.php @@ -1,84 +1,84 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.0.0 - */ - - class owa_subStringPositionValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $value = $this->getValues(); - - $substring = $this->getConfig('substring'); - - $pos = strpos($value, $substring); - - $operator = $this->getConfig('operator'); - $position = $this->getConfig('position'); - - switch ($operator) { - - case "=": - - if ($pos === $position) { - ; - } else { - $this->hasError(); - } - - - break; - - case "!=": - - if ($pos === $position) { - $this->hasError(); - } - - break; - } - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $error = $this->setErrorMessage(sprintf('The string "%s" was found within the value at position %d', $substring, $pos)); - } - - - - } - - } - - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.0.0 + */ + + class owa_subStringPositionValidation extends owa_validation { + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $value = $this->getValues(); + + $substring = $this->getConfig('substring'); + + $pos = strpos($value, $substring); + + $operator = $this->getConfig('operator'); + $position = $this->getConfig('position'); + + switch ($operator) { + + case "=": + + if ($pos === $position) { + ; + } else { + $this->hasError(); + } + + + break; + + case "!=": + + if ($pos === $position) { + $this->hasError(); + } + + break; + } + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $error = $this->setErrorMessage(sprintf('The string "%s" was found within the value at position %d', $substring, $pos)); + } + + + + } + + } + + ?> \ No newline at end of file diff --git a/plugins/validations/userName.php b/plugins/validations/userName.php index 0335f6f65..44856fb1d 100644 --- a/plugins/validations/userName.php +++ b/plugins/validations/userName.php @@ -24,38 +24,38 @@ * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 * @category owa * @package owa - * @version $Revision$ - * @since owa 1.0.0 + * @version $Revision$ + * @since owa 1.0.0 */ class owa_userNameValidation extends owa_validation { - - function __construct() { - - return parent::__construct(); - } - - function validate() { - - $error = $this->getErrorMsg(); - - if (empty($error)) { - $this->setErrorMessage('The user name contains illegal characters.'); - } - - $u = $this->getValues(); - - $illegals = owa_coreAPI::getSetting('base', 'user_id_illegal_chars'); - - foreach ( $illegals as $k => $char ) { - - if ( strpos( $u, $char ) ) { - - $this->hasError(); - break; - } - } - } + + function __construct() { + + return parent::__construct(); + } + + function validate() { + + $error = $this->getErrorMsg(); + + if (empty($error)) { + $this->setErrorMessage('The user name contains illegal characters.'); + } + + $u = $this->getValues(); + + $illegals = owa_coreAPI::getSetting('base', 'user_id_illegal_chars'); + + foreach ( $illegals as $k => $char ) { + + if ( strpos( $u, $char ) ) { + + $this->hasError(); + break; + } + } + } } ?> \ No newline at end of file diff --git a/queue.php b/queue.php index 763513690..43f72255a 100644 --- a/queue.php +++ b/queue.php @@ -1,61 +1,61 @@ - - * @copyright Copyright © 2006 Peter Adams - * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 - * @category owa - * @package owa - * @version $Revision$ - * @since owa 1.3.0 - */ - -$owa = new owa_php(); - -if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { - - - $owa->setSetting('base', 'is_remote_event_queue', true); - $owa->e->debug('post: ' . print_r($_POST, true) ); - $raw_event = owa_coreAPI::getRequestParam('event'); - - if ( $raw_event ) { - - $dispatch = owa_coreAPI::getEventDispatch(); - $event = $dispatch->makeEvent(); - $event->loadFromArray($raw_event); - - $owa->e->debug(print_r($event,true)); - $dispatch->asyncNotify($event); - } - -} else { - // unload owa - $owa->restInPeace(); -} - + + * @copyright Copyright © 2006 Peter Adams + * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0 + * @category owa + * @package owa + * @version $Revision$ + * @since owa 1.3.0 + */ + +$owa = new owa_php(); + +if ( $owa->isEndpointEnabled( basename( __FILE__ ) ) ) { + + + $owa->setSetting('base', 'is_remote_event_queue', true); + $owa->e->debug('post: ' . print_r($_POST, true) ); + $raw_event = owa_coreAPI::getRequestParam('event'); + + if ( $raw_event ) { + + $dispatch = owa_coreAPI::getEventDispatch(); + $event = $dispatch->makeEvent(); + $event->loadFromArray($raw_event); + + $owa->e->debug(print_r($event,true)); + $dispatch->asyncNotify($event); + } + +} else { + // unload owa + $owa->restInPeace(); +} + ?> \ No newline at end of file diff --git a/wp_plugin.php b/wp_plugin.php index 8f4f5cc41..9b53a7907 100644 --- a/wp_plugin.php +++ b/wp_plugin.php @@ -1,831 +1,831 @@ - true, - 'feed_tracking_medium' => 'feed', - 'feed_subscription_param' => 'owa_sid' - ); - - /** - * Constructor - * - */ - function __construct() { - - // needed??? - ob_start(); - - // fetch plugin options from DB and combine them with defaults. - $options = get_option( 'owa_wp_plugin' ); - - if ( $options ) { - - $this->options = array_merge_recursive($this->options, $options); - } - - /* register WordPress hooks and filters. */ - - // insert javascript tracking tag - add_action('wp_head', array( $this,'insertTrackingTag' ), 100 ); - - // add tracking to feed entry permalinks - add_filter('the_permalink_rss', array( $this, 'decorateFeedEntryPermalink' ) ); - - // add tracking to feed subscription links - add_filter('bloginfo_url', array($this, 'decorateFeedSubscriptionLink' ) ); - - // register settings page - // - - // Actions if OWA is available as a library - if( $this->isOwaAvailable() ) { - - // handle API calls and other requests - add_action('init', array( $this, 'handleSpecialActionRequest' ) ); - - // @todo find a way for these methods to POST these to the OWA instance instead of via OWA's PHP Tracker - $this->defineActionHooks(); - - // Register admin pages - add_action('admin_menu', array( $this, 'registerAdminPages' ) ); - - // Create a new tracked site in OWA. - // @todo move this to REST API call when it's ready. - add_action('wpmu_new_blog', array($this, 'createTrackedSiteForNewBlog'), 10, 6); - - // Installation hook - register_activation_hook(__FILE__, 'owa_install'); - - } - } - - /** - * Get an option value - */ - function getOption( $key ) { - - $options = array(); - $options = $this->options; - if ( array_key_exists( $key, $options ) ) { - - return $this->options[ $key ]; - } - } - - /** - * Set an option value - */ - function setOption( $key, $value ) { - - $this->options[ $key ] = $value; - } - - /** - * Singelton - */ - static function getInstance() { - - static $o; - - if ( ! isset( $o ) ) { - - $o = new owa_wp_plugin(); - } - - return $o; - } - - /** - * Callback for admin_menu hook - */ - function registerAdminPages() { - - if (function_exists('add_submenu_page')) { - - if ( $this->isOwaAvailable() ) { - - add_submenu_page('index.php', 'OWA Dashboard', 'OWA Dashboard', 1, dirname(__FILE__), array( $this, 'pageController') ); - } - - if (function_exists('add_options_page')) { - - add_options_page('OWA Options', 'OWA', 8, basename(__FILE__), array($this, 'options_page') ); - } - } - } - - /** - * Callback for reporting dashboard/pages - */ - function pageController() { - - if ( $this->isOwaAvailable() ) { - - $owa = $this->getOwaInstance(); - echo $owa->handleRequest(); - } - } - - /** - * Callback for OWA settings page - */ - function options_page() { - - $owa = $this->getOwaInstance(); - - $params = array(); - - $params['do'] = owa_coreAPI::getRequestParam( 'do' ); - - if ( ! $params['do'] ) { - - $params['do'] = 'base.optionsGeneral'; - } - - echo $owa->handleRequest($params); - - } - - /** - * Hooks for tracking WordPress Admin actions - */ - function defineActionHooks() { - - - // These hooks rely on accessing OWA server-side - // as a PHP object. - - if ( $this->isOwaAvailable() ) { - - // New Comment - add_action( 'comment_post', array( $this, 'trackCommentAction' ), 10, 2); - // Comment Edit - add_action( 'transition_comment_status', array( $this, 'trackCommentEditAction' ), 10, 3); - // User Registration - add_action( 'user_register', array( $this, 'trackUserRegistrationAction' ) ); - // user login - add_action( 'wp_login', array( $this, 'trackUserLoginAction' ) ); - // User Profile Update - add_action( 'profile_update', array( $this, 'trackUserProfileUpdateAction' ), 10, 2); - // Password Reset - add_action( 'password_reset', array( $this, 'trackPasswordResetAction' ) ); - // Trackback - add_action( 'trackback_post', array( $this, 'trackTrackbackAction' ) ); - // New Attachment - add_action( 'add_attachment', array( $this, 'trackAttachmentCreatedAction' ) ); - // Attachment Edit - add_action( 'edit_attachment', array( $this, 'trackAttachmentEditAction' ) ); - // Post Edit - add_action( 'transition_post_status', array( $this, 'trackPostAction') , 10, 3); - // New Blog (WPMU) - add_action( 'wpmu_new_blog', array( $this, 'trackNewBlogAction') , 10, 5); - - - // track feeds - add_action('init', array( $this, 'addFeedTrackingQueryParams')); - add_action( 'template_redirect', array( $this, 'trackFeedRequest'), 1 ); - - } - - // These hooks do NOT rely on OWA being accessable via PHP - - } - - /** - * OWA Schema and setting installation - * - */ - function install() { - - define('OWA_INSTALLING', true); - - $params = array(); - //$params['do_not_fetch_config_from_db'] = true; - - $owa = $this->getOwaInstance($params); - $owa->setSetting('base', 'cache_objects', false); - $public_url = get_bloginfo('wpurl').'/wp-content/plugins/owa/'; - - $install_params = array('site_id' => md5(get_option('siteurl')), - 'name' => get_bloginfo('name'), - 'domain' => get_option('siteurl'), - 'description' => get_bloginfo('description'), - 'action' => 'base.installEmbedded', - 'db_type' => 'mysql', - 'db_name' => DB_NAME, - 'db_host' => DB_HOST, - 'db_user' => DB_USER, - 'db_password' => DB_PASSWORD, - 'public_url' => $public_url - ); - - $owa->handleRequest($install_params); - } - - function handleSpecialActionRequest() { - - $owa = $this->getOwaInstance(); - - owa_coreAPI::debug("hello from WP special action handler"); - - return $owa->handleSpecialActionRequest(); - } - - - // Add query vars to WordPress - function addFeedTrackingQueryParams() { - - global $wp; - - // feed tracking param - $wp->add_query_var('owa_sid'); - - } - - /** - * Determines the title of the page being requested - * - * @param string $page_type - * @return string $title - */ - function getPageTitle() { - - $page_type = $this->getPageType(); - - if ( $page_type == "Home" ) { - - $title = get_bloginfo( "name" ); - - } elseif ( $page_type == "Search Results" ) { - - $title = "Search Results for \"" . get_search_query() . "\""; - - } else { - - $title = wp_title($sep = '', $display = 0); - } - - return $title; - } - - function setPageTitle() { - - $this->cmds[] = sprintf("owa_cmds.push(['setPageTitle', '%s' ]);", $this->getPageTitle() ); - } - - /** - * Determines the type of WordPress page - * - * @return string $type - */ - function getPageType() { - - if ( is_home() ) { - $type = "Home"; - } elseif ( is_attachment() ){ - $type = "Attachment"; - } elseif ( is_page() ) { - $type = "Page"; - // general page catch, should be after more specific post types - } elseif ( is_single() ) { - $type = "Post"; - } elseif ( is_feed() ) { - $type = "Feed"; - } elseif ( is_author() ) { - $type = "Author"; - } elseif ( is_category() ) { - $type = "Category"; - } elseif ( is_search() ) { - $type = "Search Results"; - } elseif ( is_month() ) { - $type = "Month"; - } elseif ( is_day() ) { - $type = "Day"; - } elseif ( is_year() ) { - $type = "Year"; - } elseif ( is_time() ) { - $type = "Time"; - } elseif ( is_tag() ) { - $type = "Tag"; - } elseif ( is_tax() ) { - $type = "Taxonomy"; - // general archive catch, should be after specific archive types - } elseif ( is_archive() ) { - $type = "Archive"; - } else { - $type = '(not set)'; - } - - return $type; - } - - function setPageType() { - - $this->cmds[] = sprintf("owa_cmds.push(['setPageType', '%s' ]);", $this->getPageType() ); - } - - function cmdsToString() { - - $out = ''; - - foreach ( $this->cmds as $cmd ) { - - $out .= $cmd . " \n"; - } - - return $out; - } - - // check to see if OWA is available as a php library on the same server - function isOwaAvailable() { - - return true; - } - - // gets an instance of your OWA as a php object - function getOwaInstance() { - - static $owa; - - if( empty( $owa ) ) { - - if ( $this->isOwaAvailable() ) { - - require_once('owa_env.php'); - require_once(OWA_BASE_CLASSES_DIR.'owa_php.php'); - - // create owa instance w/ config - $owa = new owa_php(); - $owa->setSiteId( md5( get_option( 'siteurl' ) ) ); - $owa->setSetting( 'base', 'report_wrapper', 'wrapper_wordpress.tpl' ); - $owa->setSetting( 'base', 'link_template', '%s&%s' ); - $owa->setSetting( 'base', 'main_url', '../wp-admin/index.php?page=owa' ); - $owa->setSetting( 'base', 'main_absolute_url', get_bloginfo('url').'/wp-admin/index.php?page=owa' ); - $owa->setSetting( 'base', 'action_url', get_bloginfo('url').'/index.php?owa_specialAction' ); - $owa->setSetting( 'base', 'api_url', get_bloginfo('url').'/index.php?owa_apiAction' ); - $owa->setSetting( 'base', 'is_embedded', true ); - - - // register allowedSitesList filter - $dispatch = owa_coreAPI::getEventDispatch(); - // alternative auth method, sets auth status, role, and allowed sites list. - $dispatch->attachFilter('auth_status', 'owa_wp_plugin::wpAuthUser', 0); - } - } - - return $owa; - } - - /** - * OWA Authenication filter - * - * Uses WordPress priviledge system to determine OWA authentication levels. - * - * @return boolean - */ - static function wpAuthUser($auth_status) { - - $current_user = wp_get_current_user(); - - if ( $current_user instanceof WP_User ) { - // logged in, authenticated - $cu = owa_coreAPI::getCurrentUser(); - - $cu->setAuthStatus(true); - - if (isset($current_user->user_login)) { - $cu->setUserData('user_id', $current_user->user_login); - owa_coreAPI::debug("Wordpress User_id: ".$current_user->user_login); - } - - if (isset($current_user->user_email)) { - $cu->setUserData('email_address', $current_user->user_email); - } - - if (isset($current_user->first_name)) { - $cu->setUserData('real_name', $current_user->first_name.' '.$current_user->last_name); - $cu->setRole( owa_wp_plugin::translateAuthRole( $current_user->roles ) ); - } - - owa_coreAPI::debug("Wordpress User Role: ".print_r($current_user->roles, true)); - owa_coreAPI::debug("Wordpress Translated OWA User Role: ".$cu->getRole()); - - // fetch the list of allowed blogs from WP - $domains = array(); - $allowedBlogs = get_blogs_of_user($current_user->ID); - - foreach ( $allowedBlogs as $blog) { - $domains[] = $blog->siteurl; - } - - // check to see if we are installing before trying to load sites - // other wise you run into a race condition as config file - // might not be created. - if (! defined('OWA_INSTALLING') ) { - // load assigned sites list by domain - $cu->loadAssignedSitesByDomain($domains); - } - - $cu->setInitialized(); - - return true; - - } else { - // not logged in to WP and therefor not authenticated - return false; - } - } - - /** - * Translate WordPress to OWA Authentication Roles - * - * @param $roles array array of WP roles - * @return string - */ - static function translateAuthRole( $roles ) { - - if (!empty($roles)) { - - if (in_array('administrator', $roles)) { - $owa_role = 'admin'; - } elseif (in_array('editor', $roles)) { - $owa_role = 'viewer'; - } elseif (in_array('author', $roles)) { - $owa_role = 'viewer'; - } elseif (in_array('contributor', $roles)) { - $owa_role = 'viewer'; - } elseif (in_array('subscriber', $roles)) { - $owa_role = 'everyone'; - } else { - $owa_role = 'everyone'; - } - - } else { - $owa_role = 'everyone'; - } - - return $owa_role; - } - - /** - * Insert Tracking Tag - * - * Adds javascript tracking tag int of all pages. - * - */ - function insertTrackingTag() { - - // Don't log if the page request is a preview - Wordpress 2.x or greater - if ( function_exists( 'is_preview' ) ) { - - if ( is_preview() ) { - - return; - } - } - - // dont log customizer previews either. - if ( function_exists( 'is_customize_preview' ) ) { - - if ( is_customize_preview() ) { - - return; - } - } - - // dont log requests for admin interface pages. - if ( function_exists( ' is_admin' ) && is_admin() ) { - - return; - } - - - // get instance of OWA - $owa = $this->getOwaInstance(); - - // set any cmds - $this->setPageType(); - $this->setPageTitle(); - - // convert cmds to string and pass to tracking tag template - $options = array( 'cmds' => $this->cmdsToString() ); - - // place the tracking tag - $owa->placeHelperPageTags(true, $options); - } - - /** - * Adds tracking source param to links in feeds - * - * @param string $link - * @return string - */ - function decorateFeedEntryPermalink($link) { - - // check for presence of '?' which is not present under URL rewrite conditions - - if ( $this->getOption( 'track_feed_links' ) ) { - - if ( strpos($link, "?") === false ) { - // add the '?' if not found - $link .= '?'; - } - - // setup link template - $link_template = "%s&%s=%s&%s=%s"; - - return sprintf($link_template, - $link, - 'owa_medium', - $this->getOption( 'feed_tracking_medium' ), - $this->getOption( 'feed_subscription_param' ), - $_GET[ $this->getOption( 'feed_subscription_param' ) ] - ); - } - } - - /** - * Wordpress filter function adds a GUID to the feed URL. - * - * @param array $binfo - * @return string $newbinfo - */ - function decorateFeedSubscriptionLink( $binfo ) { - - $is_feed = strpos($binfo, "feed="); - - if ( $is_feed && $this->getOption( 'track_feed_links' ) ) { - - $guid = crc32(getmypid().microtime()); - - $newbinfo = $binfo . "&" . $this->getOption('feed_subscription_param') . "=" . $guid; - - } else { - - $newbinfo = $binfo; - } - - return $newbinfo; - } - - // create a new tracked site. - function createTrackedSiteForNewBlog($blog_id, $user_id, $domain, $path, $site_id, $meta) { - - $owa = $this->getOwaInstance(); - $sm = owa_coreAPI::supportClassFactory( 'base', 'siteManager' ); - $sm->createNewSite( $domain, $domain, '', ''); - } - - - /** - * New Blog Action Tracker - */ - function trackNewBlogAction( $blog_id, $user_id, $domain, $path, $site_id ) { - - $owa = $this->getOwaInstance(); - $owa->trackAction('WordPress', 'Blog Created', $domain); - } - - /** - * Edit Post Action Tracker - */ - function trackedPostEditAction( $post_id, $post ) { - - // we don't want to track autosaves... - if( wp_is_post_autosave( $post ) ) { - - return; - } - - $owa = $this->getOwaInstance(); - $label = $post->post_title; - $owa->trackAction( 'WordPress', $post->post_type.' edited', $label ); - } - - /** - * Post Action Tracker - * - * Trackes new and edited post actions. Including custom post types. - */ - function trackPostAction( $new_status, $old_status, $post ) { - - $action_name = ''; - - // we don't want to track autosaves... - if(wp_is_post_autosave( $post ) ) { - - return; - } - - // or drafts - if ( $new_status === 'draft' && $old_status === 'draft' ) { - - return; - - } - - // set action label - if ( $new_status === 'publish' && $old_status != 'publish' ) { - - $action_name = $post->post_type.' publish'; - - } elseif ( $new_status === $old_status ) { - - $action_name = $post->post_type.' edit'; - } - - // track action - if ( $action_name ) { - - - $owa = $this->getOwaInstance(); - owa_coreAPI::debug(sprintf("new: %s, old: %s, post: %s", $new_status, $old_status, print_r($post, true))); - $label = $post->post_title; - - $owa->trackAction('WordPress', $action_name, $label); - } - } - - /** - * Edit Attachment Action Tracker - */ - function trackAttachmentEditAction( $post_id ) { - - $owa = $this->getOwaInstance(); - $post = get_post( $post_id ); - $label = $post->post_title; - $owa->trackAction('WordPress', 'Attachment Edit', $label); - } - - /** - * New Attachment Action Tracker - */ - function trackAttachmentCreatedAction( $post_id ) { - - $owa = $this->getOwaInstance(); - $post = get_post($post_id); - $label = $post->post_title; - $owa->trackAction('WordPress', 'Attachment Created', $label); - } - - /** - * User Registration Action Tracker - */ - function trackUserRegistrationAction( $user_id ) { - - $owa = $this->getOwaInstance(); - $user = get_userdata($user_id); - if (!empty($user->first_name) && !empty($user->last_name)) { - $label = $user->first_name.' '.$user->last_name; - } else { - $label = $user->display_name; - } - - $owa->trackAction('WordPress', 'User Registration', $label); - } - - /** - * User Login Action Tracker - */ - function trackUserLoginAction( $user_id ) { - - $owa = $this->getOwaInstance(); - $label = $user_id; - $owa->trackAction('WordPress', 'User Login', $label); - } - - /** - * Profile Update Action Tracker - */ - function trackUserProfileUpdateAction( $user_id, $old_user_data = '' ) { - - $owa = $this->getOwaInstance(); - $user = get_userdata($user_id); - if (!empty($user->first_name) && !empty($user->last_name)) { - $label = $user->first_name.' '.$user->last_name; - } else { - $label = $user->display_name; - } - - $owa->trackAction('WordPress', 'User Profile Update', $label); - } - - /** - * Password Reset Action Tracker - */ - function trackPasswordResetAction( $user ) { - - $owa = $this->getOwaInstance(); - $label = $user->display_name; - $owa->trackAction('WordPress', 'User Password Reset', $label); - } - - /** - * Trackback Action Tracker - */ - function trackTrackbackAction( $comment_id ) { - - $owa = $this->getOwaInstance(); - $label = $comment_id; - $owa->trackAction('WordPress', 'Trackback', $label); - } - - function trackCommentAction( $id, $comment_data = '' ) { - - if ( $comment_data === 'approved' || $comment_data === 1 ) { - - $owa = $this->getOwaInstance(); - $label = ''; - $owa->trackAction('WordPress', 'comment', $label); - } - } - - function trackCommentEditAction( $new_status, $old_status, $comment ) { - - if ($new_status === 'approved') { - - if (isset($comment->comment_author)) { - - $label = $comment->comment_author; - - } else { - - $label = ''; - } - - $owa = $this->getOwaInstance(); - $owa->trackAction('WordPress', 'comment', $label); - } - } - - // Tracks feed requests - function trackFeedRequest() { - - if ( is_feed() ) { - - - $owa = $this->getOwaInstance(); - - if( $owa->getSetting( 'base', 'log_feedreaders') ) { - - owa_coreAPI::debug('Tracking WordPress feed request'); - - $event = $owa->makeEvent(); - // set event type - $event->setEventType( 'base.feed_request' ); - // determine and set the type of feed - $event->set( 'feed_format', get_query_var( 'feed' ) ); - $event->set( 'feed_subscription_id', get_query_var( 'owa_sid' ) ); - //$event->set( 'feed_subscription_id', $_GET['owa_sid'] ); - // track - $owa->trackEvent( $event ); - } - } - } - -} - + true, + 'feed_tracking_medium' => 'feed', + 'feed_subscription_param' => 'owa_sid' + ); + + /** + * Constructor + * + */ + function __construct() { + + // needed??? + ob_start(); + + // fetch plugin options from DB and combine them with defaults. + $options = get_option( 'owa_wp_plugin' ); + + if ( $options ) { + + $this->options = array_merge_recursive($this->options, $options); + } + + /* register WordPress hooks and filters. */ + + // insert javascript tracking tag + add_action('wp_head', array( $this,'insertTrackingTag' ), 100 ); + + // add tracking to feed entry permalinks + add_filter('the_permalink_rss', array( $this, 'decorateFeedEntryPermalink' ) ); + + // add tracking to feed subscription links + add_filter('bloginfo_url', array($this, 'decorateFeedSubscriptionLink' ) ); + + // register settings page + // + + // Actions if OWA is available as a library + if( $this->isOwaAvailable() ) { + + // handle API calls and other requests + add_action('init', array( $this, 'handleSpecialActionRequest' ) ); + + // @todo find a way for these methods to POST these to the OWA instance instead of via OWA's PHP Tracker + $this->defineActionHooks(); + + // Register admin pages + add_action('admin_menu', array( $this, 'registerAdminPages' ) ); + + // Create a new tracked site in OWA. + // @todo move this to REST API call when it's ready. + add_action('wpmu_new_blog', array($this, 'createTrackedSiteForNewBlog'), 10, 6); + + // Installation hook + register_activation_hook(__FILE__, 'owa_install'); + + } + } + + /** + * Get an option value + */ + function getOption( $key ) { + + $options = array(); + $options = $this->options; + if ( array_key_exists( $key, $options ) ) { + + return $this->options[ $key ]; + } + } + + /** + * Set an option value + */ + function setOption( $key, $value ) { + + $this->options[ $key ] = $value; + } + + /** + * Singelton + */ + static function getInstance() { + + static $o; + + if ( ! isset( $o ) ) { + + $o = new owa_wp_plugin(); + } + + return $o; + } + + /** + * Callback for admin_menu hook + */ + function registerAdminPages() { + + if (function_exists('add_submenu_page')) { + + if ( $this->isOwaAvailable() ) { + + add_submenu_page('index.php', 'OWA Dashboard', 'OWA Dashboard', 1, dirname(__FILE__), array( $this, 'pageController') ); + } + + if (function_exists('add_options_page')) { + + add_options_page('OWA Options', 'OWA', 8, basename(__FILE__), array($this, 'options_page') ); + } + } + } + + /** + * Callback for reporting dashboard/pages + */ + function pageController() { + + if ( $this->isOwaAvailable() ) { + + $owa = $this->getOwaInstance(); + echo $owa->handleRequest(); + } + } + + /** + * Callback for OWA settings page + */ + function options_page() { + + $owa = $this->getOwaInstance(); + + $params = array(); + + $params['do'] = owa_coreAPI::getRequestParam( 'do' ); + + if ( ! $params['do'] ) { + + $params['do'] = 'base.optionsGeneral'; + } + + echo $owa->handleRequest($params); + + } + + /** + * Hooks for tracking WordPress Admin actions + */ + function defineActionHooks() { + + + // These hooks rely on accessing OWA server-side + // as a PHP object. + + if ( $this->isOwaAvailable() ) { + + // New Comment + add_action( 'comment_post', array( $this, 'trackCommentAction' ), 10, 2); + // Comment Edit + add_action( 'transition_comment_status', array( $this, 'trackCommentEditAction' ), 10, 3); + // User Registration + add_action( 'user_register', array( $this, 'trackUserRegistrationAction' ) ); + // user login + add_action( 'wp_login', array( $this, 'trackUserLoginAction' ) ); + // User Profile Update + add_action( 'profile_update', array( $this, 'trackUserProfileUpdateAction' ), 10, 2); + // Password Reset + add_action( 'password_reset', array( $this, 'trackPasswordResetAction' ) ); + // Trackback + add_action( 'trackback_post', array( $this, 'trackTrackbackAction' ) ); + // New Attachment + add_action( 'add_attachment', array( $this, 'trackAttachmentCreatedAction' ) ); + // Attachment Edit + add_action( 'edit_attachment', array( $this, 'trackAttachmentEditAction' ) ); + // Post Edit + add_action( 'transition_post_status', array( $this, 'trackPostAction') , 10, 3); + // New Blog (WPMU) + add_action( 'wpmu_new_blog', array( $this, 'trackNewBlogAction') , 10, 5); + + + // track feeds + add_action('init', array( $this, 'addFeedTrackingQueryParams')); + add_action( 'template_redirect', array( $this, 'trackFeedRequest'), 1 ); + + } + + // These hooks do NOT rely on OWA being accessable via PHP + + } + + /** + * OWA Schema and setting installation + * + */ + function install() { + + define('OWA_INSTALLING', true); + + $params = array(); + //$params['do_not_fetch_config_from_db'] = true; + + $owa = $this->getOwaInstance($params); + $owa->setSetting('base', 'cache_objects', false); + $public_url = get_bloginfo('wpurl').'/wp-content/plugins/owa/'; + + $install_params = array('site_id' => md5(get_option('siteurl')), + 'name' => get_bloginfo('name'), + 'domain' => get_option('siteurl'), + 'description' => get_bloginfo('description'), + 'action' => 'base.installEmbedded', + 'db_type' => 'mysql', + 'db_name' => DB_NAME, + 'db_host' => DB_HOST, + 'db_user' => DB_USER, + 'db_password' => DB_PASSWORD, + 'public_url' => $public_url + ); + + $owa->handleRequest($install_params); + } + + function handleSpecialActionRequest() { + + $owa = $this->getOwaInstance(); + + owa_coreAPI::debug("hello from WP special action handler"); + + return $owa->handleSpecialActionRequest(); + } + + + // Add query vars to WordPress + function addFeedTrackingQueryParams() { + + global $wp; + + // feed tracking param + $wp->add_query_var('owa_sid'); + + } + + /** + * Determines the title of the page being requested + * + * @param string $page_type + * @return string $title + */ + function getPageTitle() { + + $page_type = $this->getPageType(); + + if ( $page_type == "Home" ) { + + $title = get_bloginfo( "name" ); + + } elseif ( $page_type == "Search Results" ) { + + $title = "Search Results for \"" . get_search_query() . "\""; + + } else { + + $title = wp_title($sep = '', $display = 0); + } + + return $title; + } + + function setPageTitle() { + + $this->cmds[] = sprintf("owa_cmds.push(['setPageTitle', '%s' ]);", $this->getPageTitle() ); + } + + /** + * Determines the type of WordPress page + * + * @return string $type + */ + function getPageType() { + + if ( is_home() ) { + $type = "Home"; + } elseif ( is_attachment() ){ + $type = "Attachment"; + } elseif ( is_page() ) { + $type = "Page"; + // general page catch, should be after more specific post types + } elseif ( is_single() ) { + $type = "Post"; + } elseif ( is_feed() ) { + $type = "Feed"; + } elseif ( is_author() ) { + $type = "Author"; + } elseif ( is_category() ) { + $type = "Category"; + } elseif ( is_search() ) { + $type = "Search Results"; + } elseif ( is_month() ) { + $type = "Month"; + } elseif ( is_day() ) { + $type = "Day"; + } elseif ( is_year() ) { + $type = "Year"; + } elseif ( is_time() ) { + $type = "Time"; + } elseif ( is_tag() ) { + $type = "Tag"; + } elseif ( is_tax() ) { + $type = "Taxonomy"; + // general archive catch, should be after specific archive types + } elseif ( is_archive() ) { + $type = "Archive"; + } else { + $type = '(not set)'; + } + + return $type; + } + + function setPageType() { + + $this->cmds[] = sprintf("owa_cmds.push(['setPageType', '%s' ]);", $this->getPageType() ); + } + + function cmdsToString() { + + $out = ''; + + foreach ( $this->cmds as $cmd ) { + + $out .= $cmd . " \n"; + } + + return $out; + } + + // check to see if OWA is available as a php library on the same server + function isOwaAvailable() { + + return true; + } + + // gets an instance of your OWA as a php object + function getOwaInstance() { + + static $owa; + + if( empty( $owa ) ) { + + if ( $this->isOwaAvailable() ) { + + require_once('owa_env.php'); + require_once(OWA_BASE_CLASSES_DIR.'owa_php.php'); + + // create owa instance w/ config + $owa = new owa_php(); + $owa->setSiteId( md5( get_option( 'siteurl' ) ) ); + $owa->setSetting( 'base', 'report_wrapper', 'wrapper_wordpress.tpl' ); + $owa->setSetting( 'base', 'link_template', '%s&%s' ); + $owa->setSetting( 'base', 'main_url', '../wp-admin/index.php?page=owa' ); + $owa->setSetting( 'base', 'main_absolute_url', get_bloginfo('url').'/wp-admin/index.php?page=owa' ); + $owa->setSetting( 'base', 'action_url', get_bloginfo('url').'/index.php?owa_specialAction' ); + $owa->setSetting( 'base', 'api_url', get_bloginfo('url').'/index.php?owa_apiAction' ); + $owa->setSetting( 'base', 'is_embedded', true ); + + + // register allowedSitesList filter + $dispatch = owa_coreAPI::getEventDispatch(); + // alternative auth method, sets auth status, role, and allowed sites list. + $dispatch->attachFilter('auth_status', 'owa_wp_plugin::wpAuthUser', 0); + } + } + + return $owa; + } + + /** + * OWA Authenication filter + * + * Uses WordPress priviledge system to determine OWA authentication levels. + * + * @return boolean + */ + static function wpAuthUser($auth_status) { + + $current_user = wp_get_current_user(); + + if ( $current_user instanceof WP_User ) { + // logged in, authenticated + $cu = owa_coreAPI::getCurrentUser(); + + $cu->setAuthStatus(true); + + if (isset($current_user->user_login)) { + $cu->setUserData('user_id', $current_user->user_login); + owa_coreAPI::debug("Wordpress User_id: ".$current_user->user_login); + } + + if (isset($current_user->user_email)) { + $cu->setUserData('email_address', $current_user->user_email); + } + + if (isset($current_user->first_name)) { + $cu->setUserData('real_name', $current_user->first_name.' '.$current_user->last_name); + $cu->setRole( owa_wp_plugin::translateAuthRole( $current_user->roles ) ); + } + + owa_coreAPI::debug("Wordpress User Role: ".print_r($current_user->roles, true)); + owa_coreAPI::debug("Wordpress Translated OWA User Role: ".$cu->getRole()); + + // fetch the list of allowed blogs from WP + $domains = array(); + $allowedBlogs = get_blogs_of_user($current_user->ID); + + foreach ( $allowedBlogs as $blog) { + $domains[] = $blog->siteurl; + } + + // check to see if we are installing before trying to load sites + // other wise you run into a race condition as config file + // might not be created. + if (! defined('OWA_INSTALLING') ) { + // load assigned sites list by domain + $cu->loadAssignedSitesByDomain($domains); + } + + $cu->setInitialized(); + + return true; + + } else { + // not logged in to WP and therefor not authenticated + return false; + } + } + + /** + * Translate WordPress to OWA Authentication Roles + * + * @param $roles array array of WP roles + * @return string + */ + static function translateAuthRole( $roles ) { + + if (!empty($roles)) { + + if (in_array('administrator', $roles)) { + $owa_role = 'admin'; + } elseif (in_array('editor', $roles)) { + $owa_role = 'viewer'; + } elseif (in_array('author', $roles)) { + $owa_role = 'viewer'; + } elseif (in_array('contributor', $roles)) { + $owa_role = 'viewer'; + } elseif (in_array('subscriber', $roles)) { + $owa_role = 'everyone'; + } else { + $owa_role = 'everyone'; + } + + } else { + $owa_role = 'everyone'; + } + + return $owa_role; + } + + /** + * Insert Tracking Tag + * + * Adds javascript tracking tag int of all pages. + * + */ + function insertTrackingTag() { + + // Don't log if the page request is a preview - Wordpress 2.x or greater + if ( function_exists( 'is_preview' ) ) { + + if ( is_preview() ) { + + return; + } + } + + // dont log customizer previews either. + if ( function_exists( 'is_customize_preview' ) ) { + + if ( is_customize_preview() ) { + + return; + } + } + + // dont log requests for admin interface pages. + if ( function_exists( ' is_admin' ) && is_admin() ) { + + return; + } + + + // get instance of OWA + $owa = $this->getOwaInstance(); + + // set any cmds + $this->setPageType(); + $this->setPageTitle(); + + // convert cmds to string and pass to tracking tag template + $options = array( 'cmds' => $this->cmdsToString() ); + + // place the tracking tag + $owa->placeHelperPageTags(true, $options); + } + + /** + * Adds tracking source param to links in feeds + * + * @param string $link + * @return string + */ + function decorateFeedEntryPermalink($link) { + + // check for presence of '?' which is not present under URL rewrite conditions + + if ( $this->getOption( 'track_feed_links' ) ) { + + if ( strpos($link, "?") === false ) { + // add the '?' if not found + $link .= '?'; + } + + // setup link template + $link_template = "%s&%s=%s&%s=%s"; + + return sprintf($link_template, + $link, + 'owa_medium', + $this->getOption( 'feed_tracking_medium' ), + $this->getOption( 'feed_subscription_param' ), + $_GET[ $this->getOption( 'feed_subscription_param' ) ] + ); + } + } + + /** + * Wordpress filter function adds a GUID to the feed URL. + * + * @param array $binfo + * @return string $newbinfo + */ + function decorateFeedSubscriptionLink( $binfo ) { + + $is_feed = strpos($binfo, "feed="); + + if ( $is_feed && $this->getOption( 'track_feed_links' ) ) { + + $guid = crc32(getmypid().microtime()); + + $newbinfo = $binfo . "&" . $this->getOption('feed_subscription_param') . "=" . $guid; + + } else { + + $newbinfo = $binfo; + } + + return $newbinfo; + } + + // create a new tracked site. + function createTrackedSiteForNewBlog($blog_id, $user_id, $domain, $path, $site_id, $meta) { + + $owa = $this->getOwaInstance(); + $sm = owa_coreAPI::supportClassFactory( 'base', 'siteManager' ); + $sm->createNewSite( $domain, $domain, '', ''); + } + + + /** + * New Blog Action Tracker + */ + function trackNewBlogAction( $blog_id, $user_id, $domain, $path, $site_id ) { + + $owa = $this->getOwaInstance(); + $owa->trackAction('WordPress', 'Blog Created', $domain); + } + + /** + * Edit Post Action Tracker + */ + function trackedPostEditAction( $post_id, $post ) { + + // we don't want to track autosaves... + if( wp_is_post_autosave( $post ) ) { + + return; + } + + $owa = $this->getOwaInstance(); + $label = $post->post_title; + $owa->trackAction( 'WordPress', $post->post_type.' edited', $label ); + } + + /** + * Post Action Tracker + * + * Trackes new and edited post actions. Including custom post types. + */ + function trackPostAction( $new_status, $old_status, $post ) { + + $action_name = ''; + + // we don't want to track autosaves... + if(wp_is_post_autosave( $post ) ) { + + return; + } + + // or drafts + if ( $new_status === 'draft' && $old_status === 'draft' ) { + + return; + + } + + // set action label + if ( $new_status === 'publish' && $old_status != 'publish' ) { + + $action_name = $post->post_type.' publish'; + + } elseif ( $new_status === $old_status ) { + + $action_name = $post->post_type.' edit'; + } + + // track action + if ( $action_name ) { + + + $owa = $this->getOwaInstance(); + owa_coreAPI::debug(sprintf("new: %s, old: %s, post: %s", $new_status, $old_status, print_r($post, true))); + $label = $post->post_title; + + $owa->trackAction('WordPress', $action_name, $label); + } + } + + /** + * Edit Attachment Action Tracker + */ + function trackAttachmentEditAction( $post_id ) { + + $owa = $this->getOwaInstance(); + $post = get_post( $post_id ); + $label = $post->post_title; + $owa->trackAction('WordPress', 'Attachment Edit', $label); + } + + /** + * New Attachment Action Tracker + */ + function trackAttachmentCreatedAction( $post_id ) { + + $owa = $this->getOwaInstance(); + $post = get_post($post_id); + $label = $post->post_title; + $owa->trackAction('WordPress', 'Attachment Created', $label); + } + + /** + * User Registration Action Tracker + */ + function trackUserRegistrationAction( $user_id ) { + + $owa = $this->getOwaInstance(); + $user = get_userdata($user_id); + if (!empty($user->first_name) && !empty($user->last_name)) { + $label = $user->first_name.' '.$user->last_name; + } else { + $label = $user->display_name; + } + + $owa->trackAction('WordPress', 'User Registration', $label); + } + + /** + * User Login Action Tracker + */ + function trackUserLoginAction( $user_id ) { + + $owa = $this->getOwaInstance(); + $label = $user_id; + $owa->trackAction('WordPress', 'User Login', $label); + } + + /** + * Profile Update Action Tracker + */ + function trackUserProfileUpdateAction( $user_id, $old_user_data = '' ) { + + $owa = $this->getOwaInstance(); + $user = get_userdata($user_id); + if (!empty($user->first_name) && !empty($user->last_name)) { + $label = $user->first_name.' '.$user->last_name; + } else { + $label = $user->display_name; + } + + $owa->trackAction('WordPress', 'User Profile Update', $label); + } + + /** + * Password Reset Action Tracker + */ + function trackPasswordResetAction( $user ) { + + $owa = $this->getOwaInstance(); + $label = $user->display_name; + $owa->trackAction('WordPress', 'User Password Reset', $label); + } + + /** + * Trackback Action Tracker + */ + function trackTrackbackAction( $comment_id ) { + + $owa = $this->getOwaInstance(); + $label = $comment_id; + $owa->trackAction('WordPress', 'Trackback', $label); + } + + function trackCommentAction( $id, $comment_data = '' ) { + + if ( $comment_data === 'approved' || $comment_data === 1 ) { + + $owa = $this->getOwaInstance(); + $label = ''; + $owa->trackAction('WordPress', 'comment', $label); + } + } + + function trackCommentEditAction( $new_status, $old_status, $comment ) { + + if ($new_status === 'approved') { + + if (isset($comment->comment_author)) { + + $label = $comment->comment_author; + + } else { + + $label = ''; + } + + $owa = $this->getOwaInstance(); + $owa->trackAction('WordPress', 'comment', $label); + } + } + + // Tracks feed requests + function trackFeedRequest() { + + if ( is_feed() ) { + + + $owa = $this->getOwaInstance(); + + if( $owa->getSetting( 'base', 'log_feedreaders') ) { + + owa_coreAPI::debug('Tracking WordPress feed request'); + + $event = $owa->makeEvent(); + // set event type + $event->setEventType( 'base.feed_request' ); + // determine and set the type of feed + $event->set( 'feed_format', get_query_var( 'feed' ) ); + $event->set( 'feed_subscription_id', get_query_var( 'owa_sid' ) ); + //$event->set( 'feed_subscription_id', $_GET['owa_sid'] ); + // track + $owa->trackEvent( $event ); + } + } + } + +} + ?> \ No newline at end of file