Exemplo n.º 1
0
 protected function initializeForPage()
 {
     $this->handleRequest($this->args);
     $modules = $this->getModuleCustomizeList();
     $moduleIDs = array();
     $disabledModuleIDs = array();
     foreach ($modules as $id => $info) {
         $moduleIDs[] = $id;
         if ($info['disabled']) {
             $disabledModuleIDs[] = $id;
         }
     }
     switch ($this->pagetype) {
         case 'compliant':
         case 'tablet':
             $this->addInlineJavascript('var modules = ' . json_encode($moduleIDs) . ';' . 'var disabledModules = ' . json_encode($disabledModuleIDs) . ';' . 'var MODULE_ORDER_COOKIE = "' . self::MODULE_ORDER_COOKIE . '";' . 'var DISABLED_MODULES_COOKIE = "' . self::DISABLED_MODULES_COOKIE . '";' . 'var MODULE_ORDER_COOKIE_LIFESPAN = ' . Kurogo::getSiteVar('MODULE_ORDER_COOKIE_LIFESPAN') . ';' . 'var COOKIE_PATH = "' . COOKIE_PATH . '";');
             $this->addInlineJavascriptFooter('init();');
             break;
         case 'touch':
         case 'basic':
             foreach ($moduleIDs as $index => $id) {
                 $modules[$id]['toggleDisabledURL'] = $this->buildBreadcrumbURL('index', array('action' => $modules[$id]['disabled'] ? 'on' : 'off', 'module' => $id), false);
                 if ($index > 0) {
                     $modules[$id]['swapUpURL'] = $this->buildBreadcrumbURL('index', array('action' => 'swap', 'module1' => $id, 'module2' => $moduleIDs[$index - 1]), false);
                 }
                 if ($index < count($moduleIDs) - 1) {
                     $modules[$id]['swapDownURL'] = $this->buildBreadcrumbURL('index', array('action' => 'swap', 'module1' => $id, 'module2' => $moduleIDs[$index + 1]), false);
                 }
             }
             break;
         default:
             break;
     }
     $this->assignByRef('modules', $modules);
 }
Exemplo n.º 2
0
 public function log($priority, $message, $area, $backTrace = null)
 {
     if (!self::isValidPriority($priority)) {
         throw new Exception("Invalid logging priority {$priority}");
     }
     if (!preg_match("/^[a-z0-9_-]+\$/i", $area)) {
         throw new Exception("Invalid area {$area}");
     }
     //don't log items above the current logging level
     $loggingLevel = isset($this->areaLevel[$area]) ? $this->areaLevel[$area] : $this->defaultLevel;
     if ($priority > $loggingLevel) {
         return;
     }
     if (!$backTrace) {
         $backTrace = debug_backtrace();
     }
     $compactTrace = self::compactTrace($backTrace);
     if (isset($_SERVER['REQUEST_URI'])) {
         $request = $_SERVER['REQUEST_URI'];
     } elseif (defined('KUROGO_SHELL')) {
         $request = json_encode(Kurogo::getArrayForRequest());
     } else {
         $request = null;
     }
     $content = sprintf("%s\t%s:%s\t%s\t%s\t%s", date(Kurogo::getSiteVar('LOG_DATE_FORMAT')), $area, self::priorityToString($priority), $compactTrace, $request, $message) . PHP_EOL;
     self::fileAppend($this->logFile, $content);
 }
Exemplo n.º 3
0
 public function init($args)
 {
     if (isset($args['HALT_ON_PARSE_ERRORS'])) {
         $this->haltOnParseErrors($args['HALT_ON_PARSE_ERRORS']);
     }
     $this->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
 }
Exemplo n.º 4
0
    protected function getDataController($categoryPath, &$listItemPath) {
        if (!$this->feeds)
            $this->feeds = $this->loadFeedData();

        if ($categoryPath === NULL) {
            return MapDataController::factory('MapDataController', array(
                'JS_MAP_CLASS' => 'GoogleJSMap',
                'DEFAULT_ZOOM_LEVEL' => $this->getOptionalModuleVar('DEFAULT_ZOOM_LEVEL', 10)
                ));

        } else {
            $listItemPath = $categoryPath;
            if ($this->numGroups > 0) {
                if (count($categoryPath) < 2) {
                    $path = implode(MAP_CATEGORY_DELIMITER, $categoryPath);
                    throw new Exception("invalid category path $path for multiple feed groups");
                }
                $feedIndex = array_shift($listItemPath).MAP_CATEGORY_DELIMITER.array_shift($listItemPath);
            } else {
                $feedIndex = array_shift($listItemPath);
            }
            $feedData = $this->feeds[$feedIndex];
            $controller = MapDataController::factory($feedData['CONTROLLER_CLASS'], $feedData);
            $controller->setCategory($feedIndex);
            $controller->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
            return $controller;
        }
    }
Exemplo n.º 5
0
 public static function logView($service, $id, $page, $data, $dataLabel, $size = 0)
 {
     switch ($service) {
         case 'web':
         case 'api':
             break;
         default:
             throw new Exception("Invalid service {$service}");
             break;
     }
     $deviceClassifier = Kurogo::deviceClassifier();
     $ip = Kurogo::determineIP();
     $requestURI = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
     $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
     $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
     $visitID = self::getVisitID($service);
     if (Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
         $session = Kurogo::getSession();
         $user = $session->getUser();
     } else {
         $user = false;
     }
     $logData = array('timestamp' => time(), 'date' => date('Y-m-d H:i:s'), 'site' => SITE_KEY, 'service' => $service, 'requestURI' => $requestURI, 'referrer' => $referrer, 'referredSite' => intval(self::isFromThisSite($referrer)), 'referredModule' => intval(self::isFromModule($referrer, $id)), 'userAgent' => $userAgent, 'ip' => $ip, 'user' => $user ? $user->getUserID() : '', 'authority' => $user ? $user->getAuthenticationAuthorityIndex() : '', 'visitID' => $visitID, 'pagetype' => $deviceClassifier->getPageType(), 'platform' => $deviceClassifier->getPlatform(), 'moduleID' => $id, 'page' => $page, 'data' => $data, 'dataLabel' => $dataLabel, 'size' => $size, 'elapsed' => Kurogo::getElapsed());
     try {
         $conn = self::connection();
     } catch (KurogoDataServerException $e) {
         throw new KurogoConfigurationException("Database not configured for statistics. To disable stats, set STATS_ENABLED=0 in site.ini");
     }
     $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", Kurogo::getOptionalSiteVar("KUROGO_STATS_TABLE", "kurogo_stats_v1"), implode(",", array_keys($logData)), implode(",", array_fill(0, count($logData), '?')));
     if (!($result = $conn->query($sql, array_values($logData), db::IGNORE_ERRORS))) {
         self::createStatsTables();
         $result = $conn->query($sql, array_values($logData));
     }
     return $result;
 }
Exemplo n.º 6
0
 public function init($args)
 {
     $this->baseURL = $args['BASE_URL'];
     $this->diskCache = new DiskCache(Kurogo::getSiteVar('WMS_CACHE', 'maps'), 86400 * 7, true);
     $this->diskCache->preserveFormat();
     $filename = md5($this->baseURL);
     $metafile = $filename . '-meta.txt';
     if (!$this->diskCache->isFresh($filename)) {
         $params = array('request' => 'GetCapabilities', 'service' => 'WMS');
         $query = $this->baseURL . '?' . http_build_query($params);
         file_put_contents($this->diskCache->getFullPath($metafile), $query);
         $contents = file_get_contents($query);
         $this->diskCache->write($contents, $filename);
     } else {
         $contents = $this->diskCache->read($filename);
     }
     $this->wmsParser = new WMSDataParser();
     $this->wmsParser->parseData($contents);
     $this->enableAllLayers();
     // TODO make sure this projection is supported by the server
     $projections = $this->wmsParser->getProjections();
     if (count($projections)) {
         // make sure this is a projection we can handle
         foreach ($projections as $proj) {
             $contents = MapProjector::getProjSpecs($proj);
             if ($contents) {
                 $this->setMapProjection($proj);
             }
         }
     } else {
         $this->setMapProjection(GEOGRAPHIC_PROJECTION);
     }
 }
Exemplo n.º 7
0
 public static function errorFromException(Exception $exception) {
     $error = new KurogoError($exception->getCode(), 'Exception', $exception->getMessage());
     if(!Kurogo::getSiteVar('PRODUCTION_ERROR_HANDLER_ENABLED')) {
         $error->file = $exception->getFile();
         $error->line = $exception->getLine();
         $error->trace = $exception->getTrace();
     }
     return $error;
 }
Exemplo n.º 8
0
 public function initializeForCommand()
 {
     if (!Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
         throw new KurogoConfigurationException("Authentication is not enabled on this site");
     }
     switch ($this->command) {
         case 'logout':
             if (!$this->isLoggedIn()) {
                 $this->redirectTo('session');
             } else {
                 $session = $this->getSession();
                 $user = $this->getUser();
                 $hard = $this->getArg('hard', false);
                 $authorityIndex = $this->getArg('authority', false);
                 if ($authorityIndex) {
                     $authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex);
                 } else {
                     $authority = $user->getAuthenticationAuthority();
                 }
                 $session->logout($authority, $hard);
                 $this->redirectTo('session');
             }
             $this->setResponse($response);
             $this->setResponseVersion(1);
             break;
         case 'getuserdata':
             $key = $this->getArg('key', null);
             $user = $this->getUser();
             $response = $user->getUserData($key);
             $this->setResponse($response);
             $this->setResponseVersion(1);
             break;
         case 'session':
             $session = $this->getSession();
             $response = array('session_id' => $session->getSessionID(), 'token' => $session->getLoginToken());
             // version 2 implements multiple identities into the response
             if ($this->requestedVersion == 2) {
                 $response['users'] = array();
                 $users = $session->getUsers();
                 foreach ($users as $user) {
                     $authority = $user->getAuthenticationAuthority();
                     $response['users'][$authority->getAuthorityIndex()] = array('authority' => $authority->getAuthorityIndex(), 'authorityTitle' => $authority->getAuthorityTitle(), 'userID' => $user->getUserID(), 'name' => $user->getFullName(), 'sessiondata' => $user->getSessionData());
                 }
                 $this->setResponseVersion(2);
             } else {
                 // version 1 assumes only 1 user
                 $user = $this->getUser();
                 $response['user'] = array('authority' => $user->getAuthenticationAuthorityIndex(), 'userID' => $user->getUserID(), 'name' => $user->getFullName(), 'sessiondata' => $user->getSessionData());
                 $this->setResponseVersion(1);
             }
             $this->setResponse($response);
             break;
         default:
             $this->invalidCommand();
             break;
     }
 }
Exemplo n.º 9
0
 public static function getPhoneURL($value)
 {
     // add the local area code if missing
     if (preg_match('/^\\d{3}-?\\d{4}/', $value)) {
         $phone = Kurogo::getSiteVar('LOCAL_AREA_CODE') . $value;
     }
     // remove all non-word characters from the number
     $phone = 'tel:' . preg_replace('/\\W/', '', $value);
     return $phone;
 }
Exemplo n.º 10
0
 public static function getPhoneURL($value)
 {
     // add the local area code if missing
     if (preg_match('/^\\d{3}-?\\d{4}/', $value)) {
         $phone = Kurogo::getSiteVar('LOCAL_AREA_CODE') . $value;
     }
     // remove all non-digit characters except the character '+' for international phone numbers
     $phone = 'tel:' . preg_replace('/[^0-9\\+]/', '', $value);
     return $phone;
 }
 public function addFilter($var, $value)
 {
     switch ($var)
     {
         case 'category':
             $this->addTrumbaFilter(Kurogo::getSiteVar('CALENDAR_CATEGORY_FILTER_FIELD'), $value);
             break;
         default:
             return parent::addFilter($var, $value);
     }
 }
Exemplo n.º 12
0
    public function initializeForCommand() {  
        if (!Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
            throw new Exception("Authentication is not enabled on this site");
        }
        
        switch ($this->command) {
            case 'logout':
                if (!$this->isLoggedIn()) {
                    $this->redirectTo('session');
                } else {
                    $user = $this->getUser();
                    $authority = $user->getAuthenticationAuthority();
                    $authority->logout($this);
                    $this->redirectTo('session');
                }

                $this->setResponse($response);
                $this->setResponseVersion(1);
                break;
                
           case 'getuserdata':
                $key = $this->getArg('key', null);
                $user = $this->getUser();
                $response = $user->getUserData($key);
                $this->setResponse($response);
                $this->setResponseVersion(1);
                break;
                
           case 'session':
                $session = $this->getSession();
                $user = $this->getUser();
                
                $response = array(
                    'session_id'=>$session->getSessionID(),
                    'token'=>$session->getLoginToken(),
                    'user'=>array(
                        'authority'=>$user->getAuthenticationAuthorityIndex(),
                        'userID'=>$user->getUserID(),
                        'name'=>$user->getFullName(),
                        'sessiondata'=>$user->getSessionData()
                    )
                        
                );

                $this->setResponse($response);
                $this->setResponseVersion(1);
                break;
                
            default:
                $this->invalidCommand();
                break;
        }
    }
Exemplo n.º 13
0
 public static function factory($controllerClass, $args)
 {
     if (!class_exists($controllerClass)) {
         throw new KurogoConfigurationException("Controller class {$controllerClass} not defined");
     }
     $controller = new $controllerClass();
     $controller->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
     if (!$controller instanceof PeopleController) {
         throw new KurogoConfigurationException("{$controller} class is not a subclass of PeopleController");
     }
     $controller->init($args);
     return $controller;
 }
Exemplo n.º 14
0
 public static function factory($sessionClass, $args = array())
 {
     $args = is_array($args) ? $args : array();
     if (!class_exists($sessionClass)) {
         throw new KurogoConfigurationException("Session class {$sessionClass} not defined");
     }
     Kurogo::log(LOG_DEBUG, "Initializing session class {$sessionClass}", 'session');
     $session = new $sessionClass();
     if (!$session instanceof Session) {
         throw new KurogoConfigurationException("{$sessionClass} is not a subclass of Session");
     }
     $session->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
     $session->initialize($args);
     return $session;
 }
Exemplo n.º 15
0
 protected function getFeed($index)
 {
     if (isset($this->feeds[$index])) {
         $feedData = $this->feeds[$index];
         if (!isset($feedData['CONTROLLER_CLASS'])) {
             $feedData['CONTROLLER_CLASS'] = 'LDAPPeopleController';
         }
         $controller = PeopleController::factory($feedData['CONTROLLER_CLASS'], $feedData);
         //$controller->setAttributes($this->detailAttributes);
         $controller->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
         return $controller;
     } else {
         throw new Exception("Error getting people feed for index $index");
     }
 }
Exemplo n.º 16
0
 public function searchCampusMap($query) {
     $this->searchResults = array();
 
 	foreach ($this->feeds as $id => $feedData) {
         $controller = MapDataController::factory($feedData['CONTROLLER_CLASS'], $feedData);
         $controller->setCategory($id);
         $controller->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
         
         if ($controller->canSearch()) {
             $results = $controller->search($query);
             $this->resultCount += count($results);
             $this->searchResults = array_merge($this->searchResults, $results);
         }
 	}
 	
 	return $this->searchResults;
 }
Exemplo n.º 17
0
 private function errorHandler($sql, $errorInfo, $ignoreErrors, $catchErrorCodes)
 {
     $e = new KurogoDataException(sprintf("Error with %s: %s", $sql, $errorInfo['message']), $errorInfo['code']);
     if ($ignoreErrors) {
         $this->lastError = KurogoError::errorFromException($e);
         return;
     }
     // prevent the default error handling mechanism
     // from triggerring in the rare case of expected
     // errors such as unique field violations
     if (in_array($errorInfo[0], $catchErrorCodes)) {
         return $errorInfo;
     }
     Kurogo::log(LOG_WARNING, sprintf("%s error with %s: %s", $this->dbType, $sql, $errorInfo['message']), 'db');
     if (Kurogo::getSiteVar('DB_DEBUG')) {
         throw $e;
     }
 }
Exemplo n.º 18
0
 protected function devError()
 {
     // production
     if (Kurogo::getSiteVar('PRODUCTION_ERROR_HANDLER_ENABLED')) {
         return false;
     }
     // check for development errors
     if (isset($_GET['error'])) {
         $path = explode('/', $_GET['error']);
         $sanitizedFileName = end($path);
         $file = $path = CACHE_DIR . "/errors/" . $sanitizedFileName . ".log";
         if (file_exists($file) && ($handle = fopen($file, "r"))) {
             $msg = fread($handle, filesize($file));
             fclose($handle);
             return $msg;
         }
     }
     return false;
 }
Exemplo n.º 19
0
 public function init($args)
 {
     $args['TITLE'] = '';
     // set BASE_URL first so parent doesn't complain
     $this->isPlaces = Kurogo::getOptionalSiteVar('USE_GOOGLE_PLACES', false, 'maps');
     if ($this->isPlaces) {
         $args['BASE_URL'] = self::PLACES_BASE_URL;
         $this->apiKey = Kurogo::getSiteVar('GOOGLE_PLACES_API_KEY', 'maps');
     } else {
         $args['BASE_URL'] = self::GEOCODE_BASE_URL;
         // the Google Maps license requires that geocode results
         // be displayed with a Google Map
         $this->staticMapClass = 'GoogleStaticMap';
         $this->dynamicMapClass = 'GoogleJSMap';
     }
     $this->defaultCenter = Kurogo::getSiteVar('DEFAULT_CENTER', 'maps');
     // TODO: grab the following from config
     //   default lat/lon, radius
     parent::init($args);
 }
Exemplo n.º 20
0
 protected function initializeForPage()
 {
     //get links from module.ini [links]
     $links = $this->getOptionalModuleSection('links');
     $this->assign('links', $links);
     //get app Data
     $appData = Kurogo::getAppData();
     $this->assign('appData', $appData);
     //get module data from modules.ini
     $modulesData = $this->getOptionalModuleSections('modules');
     foreach ($modulesData as $moduleID => &$moduleData) {
         $moduleData['icon'] = Kurogo::getOptionalModuleVar('icon', $moduleID, $moduleID, 'module', 'module');
     }
     $this->assign('modulesData', $modulesData);
     $args = array();
     if (Kurogo::getSiteVar('COMPUTER_TABLET_ENABLED', 'themes')) {
         $args['setdevice'] = 'compliant';
     }
     $previewURL = $this->buildURLForModule($this->getHomeModuleID(), 'index', $args);
     $this->assign('previewURL', $previewURL);
 }
    protected function retrieveData($url)
    {
    	if (strpos($url, 'kmz') !== false) {
    	    if (!class_exists('ZipArchive')) {
    	        throw new Exception("class ZipArchive (php-zip) not available");
    	    }
            $tmpDir = Kurogo::getSiteVar('TMP_DIR');
            if (!is_writable($tmpDir)) {
    	        throw new Exception("Temporary directory $tmpDir not available");
            }
    	    $tmpFile = $tmpDir.'/tmp.kmz';

    	    copy($url, $tmpFile);
    	    $zip = new ZipArchive();
    	    $zip->open($tmpFile);
    	    $contents = $zip->getFromIndex(0);
    	    unlink($tmpFile);
    	    return $contents; // this is false on failure, same as file_get_contents
    	} else {
    	    return parent::retrieveData($url);
    	}
    }
Exemplo n.º 22
0
 public function init($args)
 {
     // alter args for initializing retriever
     if (isset($args['title'])) {
         $args['TITLE'] = $args['title'];
     }
     $this->isPlaces = Kurogo::getOptionalSiteVar('USE_GOOGLE_PLACES', false, 'maps');
     if ($this->isPlaces) {
         $args['BASE_URL'] = self::PLACES_BASE_URL;
         $this->apiKey = Kurogo::getSiteVar('GOOGLE_PLACES_API_KEY', 'maps');
     } else {
         $args['BASE_URL'] = self::GEOCODE_BASE_URL;
         // the Google Maps license requires that geocode results
         // be displayed with a Google Map
         $this->staticMapClass = 'GoogleStaticMap';
         $this->dynamicMapClass = 'GoogleJSMap';
     }
     $this->defaultCenter = $args['center'];
     if (isset($args['NEARBY_THRESHOLD'])) {
         $this->defaultRadius = $args['NEARBY_THRESHOLD'];
     }
     parent::init($args);
     $this->retriever->setCacheLifetime(1);
 }
Exemplo n.º 23
0
 public function initializeForCommand()
 {
     switch ($this->command) {
         case 'hello':
             $allmodules = $this->getAllModules();
             $homeModuleData = $this->getModuleNavigationData();
             $homeModules = array('primary' => isset($homeModuleData['primary']) ? array_keys($homeModuleData['primary']) : array(), 'secondary' => isset($homeModuleData['secondary']) ? array_keys($homeModuleData['secondary']) : array());
             foreach ($allmodules as $moduleID => $module) {
                 if ($module->isEnabled()) {
                     $home = false;
                     if (($key = array_search($moduleID, $homeModules['primary'])) !== FALSE) {
                         $home = array('type' => 'primary', 'order' => $key, 'title' => $homeModuleData['primary'][$moduleID]);
                     } elseif (($key = array_search($moduleID, $homeModules['secondary'])) !== FALSE) {
                         $home = array('type' => 'secondary', 'order' => $key);
                     }
                     $modules[] = array('id' => $module->getID(), 'tag' => $module->getConfigModule(), 'title' => $module->getModuleVar('title', 'module'), 'access' => $module->getAccess(AccessControlList::RULE_TYPE_ACCESS), 'payload' => $module->getPayload(), 'vmin' => $module->getVmin(), 'vmax' => $module->getVmax(), 'home' => $home);
                 }
             }
             $response = array('timezone' => Kurogo::getSiteVar('LOCAL_TIMEZONE'), 'version' => KUROGO_VERSION, 'modules' => $modules, 'default' => Kurogo::defaultModule());
             $this->setResponse($response);
             $this->setResponseVersion(2);
             break;
         case 'classify':
             $userAgent = $this->getArg('useragent');
             if (!$userAgent) {
                 throw new KurogoException("useragent parameter not specified");
             }
             $response = Kurogo::deviceClassifier()->classifyUserAgent($userAgent);
             $this->setResponse($response);
             $this->setResponseVersion(1);
             break;
         default:
             $this->invalidCommand();
             break;
     }
 }
Exemplo n.º 24
0
 public function __construct($baseURL) {
     $this->baseURL = $baseURL;
     $this->diskCache = new DiskCache(Kurogo::getSiteVar('WMS_CACHE'), 86400 * 7, true);
     $this->diskCache->preserveFormat();
     $filename = md5($this->baseURL);
     $metafile = $filename.'-meta.txt';
     
     if (!$this->diskCache->isFresh($filename)) {
         $params = array(
             'request' => 'GetCapabilities',
             'service' => 'WMS',
             );
         $query = $this->baseURL.'?'.http_build_query($params);
         file_put_contents($this->diskCache->getFullPath($metafile), $query);
         $contents = file_get_contents($query);
         $this->diskCache->write($contents, $filename);
     } else {
         $contents = $this->diskCache->read($filename);
     }
     $this->wmsParser = new WMSDataParser();
     $this->wmsParser->parseData($contents);
     $this->enableAllLayers();
     $this->setMapProjection(GEOGRAPHIC_PROJECTION);
 }
Exemplo n.º 25
0
  private static function getTimeSeries($system, $start, $platform=NULL, $module=NULL, $end=NULL) {
    includePackage('db');
    $output = Array();
    
    $result = self::export_stats($system);

      $sql_fields = Array();
      $sql_criteria = Array();

      if ($system == 'web')
        $table = Kurogo::getSiteVar('PAGE_VIEWS_TABLE');
      else // assume 'api'
        $table = Kurogo::getSiteVar('API_STATS_TABLE');

      if (($end === NULL) || (strtotime($end) - strtotime($start) == 86400)) {
        $sql_criteria[] = "day='$start'";
      } else {
        $sql_criteria[] = "day >= '$start' AND day < '$end'";
        $groupby = Array();
      }

      if ($platform !== NULL) {
        $sql_criteria[] = "platform='$platform'";
      } else {
        $sql_fields[] = 'platform';
      }

      if ($module !== NULL) {
        $sql_criteria[] = "module='$module'";
      } else {
        $sql_fields[] = 'module';
      }

      if (count($sql_fields) == 2 && !isset($groupby)) {
        $sql_fields[] = 'viewcount';
      } else {
        $groupby = $sql_fields;
        $sql_fields[] = 'SUM(viewcount) AS viewcount';
      }

      $sql = "SELECT " . implode(', ', $sql_fields);
      $sql .= ' FROM ' . $table . ' WHERE ' . implode(' AND ', $sql_criteria);
      $sql .= (isset($groupby) && count($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : '';

      $conn = SiteDB::connection();
      $result = $conn->query($sql);

      // results are returned as (not necessarily in this order):
      // Array('module' => ..., 'platform' => ..., 'viewcount' => ...)
      // one row per platform/module combo
      while($row = $result->fetch()) {
        $output[] = array_map('trim', $row);
      }

      if (count($output) == 1 && $output[0]['viewcount'] === NULL) {
        $output = Array();
      }

    return $output;
  }
Exemplo n.º 26
0
 public function init($args)
 {
     $this->initArgs = $args;
     if (isset($args['HALT_ON_PARSE_ERRORS'])) {
         $this->haltOnParseErrors($args['HALT_ON_PARSE_ERRORS']);
     }
     $this->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
     $cacheClass = isset($args['CACHE_CLASS']) ? $args['CACHE_CLASS'] : 'DataCache';
     $this->cache = DataCache::factory($cacheClass, $args);
 }
Exemplo n.º 27
0
 public function init($args) {
     $this->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
 }
Exemplo n.º 28
0
 /**
  * Public factory method. This is the designated way to instantiated data controllers. Takes a string
  * for the classname to load and an array of arguments. Subclasses should generally not override this
  * method, but instead override init() to provide initialization behavior
  * @param string $controllerClass the classname to instantiate
  * @param array $args an associative array of arguments that get passed to init() and the data parser
  * @return DataController a data controller object
  */
 public static function factory($controllerClass, $args = array())
 {
     $args = is_array($args) ? $args : array();
     Kurogo::log(LOG_DEBUG, "Initializing DataController {$controllerClass}", "data");
     if (!class_exists($controllerClass)) {
         throw new KurogoConfigurationException("Controller class {$controllerClass} not defined");
     }
     $controller = new $controllerClass();
     if (!$controller instanceof DataController) {
         throw new KurogoConfigurationException("{$controllerClass} is not a subclass of DataController");
     }
     $controller->setDebugMode(Kurogo::getSiteVar('DATA_DEBUG'));
     //get global options from the site data_controller section
     $args = array_merge(Kurogo::getOptionalSiteSection('data_controller'), $args);
     $controller->init($args);
     return $controller;
 }
Exemplo n.º 29
0
 protected function initializeForPage()
 {
     $nativeApp = (bool) $this->getArg('nativeApp', false);
     $this->assign('nativeApp', $nativeApp);
     // Default args to pass through forms and urls
     $defaultArgs = array();
     if ($nativeApp) {
         $defaultArgs['nativeApp'] = 1;
     }
     // If this is a native app, use the native app GA id
     if ($nativeApp) {
         $this->assign('GOOGLE_ANALYTICS_ID', Kurogo::getOptionalSiteVar('GOOGLE_ANALYTICS_NATIVE_ID'));
     }
     if (!Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
         throw new KurogoConfigurationException($this->getLocalizedString("ERROR_AUTHENTICATION_DISABLED"));
     }
     $session = $this->getSession();
     //return URL
     $urlArray = $this->extractModuleArray($this->args);
     //see if remain logged in is enabled by the administrator, then if the value has been passed (i.e. the user checked the "remember me" box)
     $allowRemainLoggedIn = Kurogo::getOptionalSiteVar('AUTHENTICATION_REMAIN_LOGGED_IN_TIME');
     if ($allowRemainLoggedIn) {
         $remainLoggedIn = $this->getArg('remainLoggedIn', 0);
     } else {
         $remainLoggedIn = 0;
     }
     // initialize
     $authenticationAuthorities = array('total' => 0, 'direct' => array(), 'indirect' => array(), 'auto' => array());
     $invalidAuthorities = array();
     // cycle through the defined authorities in the config
     foreach (AuthenticationAuthority::getDefinedAuthenticationAuthorities() as $authorityIndex => $authorityData) {
         // USER_LOGIN property determines whether the authority is used for logins (or just groups or oauth)
         $USER_LOGIN = $this->argVal($authorityData, 'USER_LOGIN', 'NONE');
         // trap the exception if the authority is invalid (usually due to misconfiguration)
         try {
             $authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex);
             $authorityData['listclass'] = $authority->getAuthorityClass();
             $authorityData['title'] = $authorityData['TITLE'];
             $authorityData['url'] = $this->buildURL('login', array_merge($urlArray, array('authority' => $authorityIndex, 'remainLoggedIn' => $remainLoggedIn, 'startOver' => 1)));
             if ($USER_LOGIN == 'FORM') {
                 $authenticationAuthorities['direct'][$authorityIndex] = $authorityData;
                 $authenticationAuthorities['total']++;
             } elseif ($USER_LOGIN == 'LINK') {
                 $authenticationAuthorities['indirect'][$authorityIndex] = $authorityData;
                 $authenticationAuthorities['total']++;
             } elseif ($USER_LOGIN == 'AUTO') {
                 $authenticationAuthorities['auto'][$authorityIndex] = $authorityData;
                 $authenticationAuthorities['total']++;
             }
         } catch (KurogoConfigurationException $e) {
             Kurogo::log(LOG_WARNING, "Invalid authority data for %s: %s", $authorityIndex, $e->getMessage(), 'auth');
             $invalidAuthorities[$authorityIndex] = $e->getMessage();
         }
     }
     //see if we have any valid authorities
     if ($authenticationAuthorities['total'] == 0) {
         $message = $this->getLocalizedString("ERROR_NO_AUTHORITIES");
         if (count($invalidAuthorities) > 0) {
             $message .= sprintf(" %s invalid authorit%s found:\n", count($invalidAuthorities), count($invalidAuthorities) > 1 ? 'ies' : 'y');
             foreach ($invalidAuthorities as $authorityIndex => $invalidAuthority) {
                 $message .= sprintf("%s: %s\n", $authorityIndex, $invalidAuthority);
             }
         }
         //we don't
         throw new KurogoConfigurationException($message);
     }
     //assign template variables
     $this->assign('authenticationAuthorities', $authenticationAuthorities);
     $this->assign('allowRemainLoggedIn', $allowRemainLoggedIn);
     if ($forgetPasswordURL = $this->getOptionalModuleVar('FORGET_PASSWORD_URL')) {
         $this->assign('FORGET_PASSWORD_URL', $this->buildBreadcrumbURL('forgotpassword', array()));
         $this->assign('FORGET_PASSWORD_TEXT', $this->getOptionalModuleVar('FORGET_PASSWORD_TEXT', $this->getLocalizedString('FORGET_PASSWORD_TEXT')));
     }
     $multipleAuthorities = count($authenticationAuthorities['direct']) + count($authenticationAuthorities['indirect']) > 1;
     switch ($this->page) {
         case 'logoutConfirm':
             //this page is presented when a specific authority is chosen and the user is presented the option to actually log out.
             $authorityIndex = $this->getArg('authority');
             if (!$this->isLoggedIn($authorityIndex)) {
                 // they aren't logged in
                 $this->redirectTo('index', $defaultArgs);
             } elseif ($user = $this->getUser($authorityIndex)) {
                 $authority = $user->getAuthenticationAuthority();
                 $this->assign('message', $this->getLocalizedString('LOGIN_SIGNED_IN_SINGLE', Kurogo::getSiteString('SITE_NAME'), $authority->getAuthorityTitle(), $user->getFullName()));
                 $this->assign('url', $this->buildURL('logout', array('authority' => $authorityIndex)));
                 $this->assign('linkText', $this->getLocalizedString('SIGN_OUT'));
                 $this->setTemplatePage('message');
             } else {
                 //This honestly should never happen
                 $this->redirectTo('index', $defaultArgs);
             }
             break;
         case 'logout':
             $authorityIndex = $this->getArg('authority');
             //hard logouts attempt to logout of the indirect service provider (must be implemented by the authority)
             $hard = $this->getArg('hard', false);
             if (!$this->isLoggedIn($authorityIndex)) {
                 //not logged in
                 $this->redirectTo('index', $defaultArgs);
             } elseif ($authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex)) {
                 $user = $this->getUser($authority);
                 //log them out
                 $result = $session->logout($authority, $hard);
             } else {
                 //This honestly should never happen
                 $this->redirectTo('index', $defaultArgs);
             }
             if ($result) {
                 $this->setLogData($user, $user->getFullName());
                 $this->logView();
                 //if they are still logged in return to the login page, otherwise go home.
                 if ($this->isLoggedIn()) {
                     $this->redirectTo('index', array_merge(array('logout' => $authorityIndex), $defaultArgs));
                 } else {
                     $this->redirectToModule($this->getHomeModuleID(), '', array('logout' => $authorityIndex));
                 }
             } else {
                 //there was an error logging out
                 $this->setTemplatePage('message');
                 $this->assign('message', $this->getLocalizedString("ERROR_SIGN_OUT"));
             }
             break;
         case 'forgotpassword':
             //redirect to forgot password url
             if ($forgetPasswordURL = $this->getOptionalModuleVar('FORGET_PASSWORD_URL')) {
                 Kurogo::redirectToURL($forgetPasswordURL);
             } else {
                 $this->redirectTo('index', $defaultArgs);
             }
             break;
         case 'login':
             //get arguments
             $login = $this->argVal($_POST, 'loginUser', '');
             $password = $this->argVal($_POST, 'loginPassword', '');
             $options = array_merge($urlArray, array('remainLoggedIn' => $remainLoggedIn), $defaultArgs);
             $session = $this->getSession();
             $session->setRemainLoggedIn($remainLoggedIn);
             $authorityIndex = $this->getArg('authority', '');
             if (!($authorityData = AuthenticationAuthority::getAuthenticationAuthorityData($authorityIndex))) {
                 //invalid authority
                 $this->redirectTo('index', $options);
             }
             if ($this->isLoggedIn($authorityIndex)) {
                 //we're already logged in
                 $this->redirectTo('index', $options);
             }
             $this->assign('authority', $authorityIndex);
             $this->assign('remainLoggedIn', $remainLoggedIn);
             $this->assign('authorityTitle', $authorityData['TITLE']);
             //if they haven't submitted the form and it's a direct login show the form
             if ($authorityData['USER_LOGIN'] == 'FORM' && empty($login)) {
                 if (!($loginMessage = $this->getOptionalModuleVar('LOGIN_DIRECT_MESSAGE'))) {
                     $loginMessage = $this->getLocalizedString('LOGIN_DIRECT_MESSAGE', Kurogo::getSiteString('SITE_NAME'));
                 }
                 $this->assign('LOGIN_DIRECT_MESSAGE', $loginMessage);
                 $this->assign('urlArray', array_merge($urlArray, $defaultArgs));
                 break;
             } elseif ($authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex)) {
                 //indirect logins handling the login process themselves. Send a return url so the indirect authority can come back here
                 if ($authorityData['USER_LOGIN'] == 'LINK') {
                     $options['return_url'] = FULL_URL_BASE . $this->configModule . '/login?' . http_build_query(array_merge($options, array('authority' => $authorityIndex)));
                 }
                 $options['startOver'] = $this->getArg('startOver', 0);
                 $result = $authority->login($login, $password, $session, $options);
             } else {
                 $this->redirectTo('index', $options);
             }
             switch ($result) {
                 case AUTH_OK:
                     $user = $this->getUser($authority);
                     $this->setLogData($user, $user->getFullName());
                     $this->logView();
                     if ($urlArray) {
                         self::redirectToArray(array_merge($urlArray, $defaultArgs));
                     } else {
                         $this->redirectToModule($this->getHomeModuleID(), '', array('login' => $authorityIndex));
                     }
                     break;
                 case AUTH_OAUTH_VERIFY:
                     // authorities that require a manual oauth verification key
                     $this->assign('verifierKey', $authority->getVerifierKey());
                     $this->setTemplatePage('oauth_verify.tpl');
                     break 2;
                 default:
                     //there was a problem.
                     if ($authorityData['USER_LOGIN'] == 'FORM') {
                         $this->assign('message', $this->getLocalizedString('ERROR_LOGIN_DIRECT'));
                         break 2;
                     } else {
                         $this->redirectTo('index', array_merge(array('messagekey' => 'ERROR_LOGIN_INDIRECT'), $options, $defaultArgs));
                     }
             }
         case 'index':
             //sometimes messages are passed. This probably has some
             if ($messagekey = $this->getArg('messagekey')) {
                 $this->assign('messagekey', $this->getLocalizedString($messagekey));
                 try {
                     $message = $this->getLocalizedString($messagekey);
                     $this->assign('message', $message);
                 } catch (KurogoException $e) {
                 }
             }
             if ($this->isLoggedIn()) {
                 //if the url is set then redirect
                 if ($urlArray) {
                     self::redirectToArray(array_merge($urlArray, $defaultArgs));
                 }
                 //if there is only 1 authority then redirect to logout confirm
                 if (!$multipleAuthorities) {
                     $user = $this->getUser();
                     $this->redirectTo('logoutConfirm', array_merge(array('authority' => $user->getAuthenticationAuthorityIndex()), $defaultArgs));
                 }
                 //more than 1 authority. There could be 1 or more actual logged in users
                 $sessionUsers = $session->getUsers();
                 $users = array();
                 //cycle through the logged in users to build a list
                 foreach ($sessionUsers as $authorityIndex => $user) {
                     $authority = $user->getAuthenticationAuthority();
                     $users[] = array('class' => $authority->getAuthorityClass(), 'title' => count($sessionUsers) > 1 ? $this->getLocalizedString("SIGN_OUT_AUTHORITY", array($authority->getAuthorityTitle(), $user->getFullName())) : $this->getLocalizedString('SIGN_OUT'), 'subtitle' => count($sessionUsers) > 1 ? $this->getLocalizedString('SIGN_OUT') : '', 'url' => $this->buildBreadcrumbURL('logout', array('authority' => $authorityIndex), false));
                     //remove the authority from the list of available authorities (since they are logged in)
                     if (isset($authenticationAuthorities['direct'][$authorityIndex])) {
                         unset($authenticationAuthorities['direct'][$authorityIndex]);
                     }
                     if (isset($authenticationAuthorities['indirect'][$authorityIndex])) {
                         unset($authenticationAuthorities['indirect'][$authorityIndex]);
                     }
                 }
                 $this->assign('users', $users);
                 // navlist of users
                 $this->assign('authenticationAuthorities', $authenticationAuthorities);
                 //list of authorities not logged in
                 $this->assign('moreAuthorities', count($authenticationAuthorities['direct']) + count($authenticationAuthorities['indirect']));
                 //see if there are any left
                 if (count($sessionUsers) == 1) {
                     //there's only on logged in user
                     $user = current($sessionUsers);
                     $authority = $user->getAuthenticationAuthority();
                     $this->assign('LOGIN_SIGNED_IN_MESSAGE', $this->getLocalizedString('LOGIN_SIGNED_IN_SINGLE', Kurogo::getSiteString('SITE_NAME'), $authority->getAuthorityTitle(), $user->getFullName()));
                 } else {
                     //there are multiple logged in users
                     $this->assign('LOGIN_SIGNED_IN_MESSAGE', $this->getLocalizedString('LOGIN_SIGNED_IN_MULTIPLE', array(Kurogo::getSiteString('SITE_NAME'))));
                 }
                 //use loggedin.tpl
                 $this->setTemplatePage('loggedin');
             } else {
                 // not logged in
                 // if there is only 1 direct authority then redirect to the login page for that authority
                 if (!$multipleAuthorities && count($authenticationAuthorities['direct'])) {
                     $this->redirectTo('login', array_merge($urlArray, array('authority' => key($authenticationAuthorities['direct'])), $defaultArgs));
                 }
                 // if there is only 1 auto authority then redirect to the login page for that authority
                 if (!$multipleAuthorities && count($authenticationAuthorities['auto']) && !$messagekey) {
                     $this->redirectTo('login', array_merge($urlArray, array('authority' => key($authenticationAuthorities['auto'])), $defaultArgs));
                 }
                 // do we have any indirect authorities?
                 if (count($authenticationAuthorities['indirect'])) {
                     if (!($indirectMessage = $this->getOptionalModuleVar('LOGIN_INDIRECT_MESSAGE'))) {
                         $indirectMessage = $this->getLocalizedString('LOGIN_INDIRECT_MESSAGE', Kurogo::getSiteString('SITE_NAME'));
                     }
                     $this->assign('LOGIN_INDIRECT_MESSAGE', $indirectMessage);
                 }
                 // the site can create their own message at the top, or it will use the default message
                 if (!($loginMessage = $this->getOptionalModuleVar('LOGIN_INDEX_MESSAGE'))) {
                     if ($multipleAuthorities) {
                         $loginMessage = $this->getLocalizedString('LOGIN_INDEX_MESSAGE_MULTIPLE', Kurogo::getSiteString('SITE_NAME'));
                     } else {
                         $loginMessage = $this->getLocalizedString('LOGIN_INDEX_MESSAGE_SINGLE', Kurogo::getSiteString('SITE_NAME'));
                     }
                 }
                 $this->assign('LOGIN_INDEX_MESSAGE', $loginMessage);
             }
             break;
     }
 }
Exemplo n.º 30
0
function exceptionHandlerForProductionAPI(Exception $exception)
{
    $bt = $exception->getTrace();
    array_unshift($bt, array('line' => $exception->getLine(), 'file' => $exception->getFile()));
    Kurogo::log(LOG_ALERT, sprintf("A %s has occured: %s", get_class($exception), $exception->getMessage()), "exception", $bt);
    if ($exception instanceof KurogoException) {
        $sendNotification = $exception->shouldSendNotification();
    } else {
        $sendNotification = true;
    }
    if ($sendNotification) {
        $to = Kurogo::getSiteVar('DEVELOPER_EMAIL');
        if (!Kurogo::deviceClassifier()->isSpider() && $to) {
            mail($to, "API experiencing problems", "The following command is throwing exceptions:\n\n" . "URL: http" . (IS_SECURE ? 's' : '') . "://" . SERVER_HOST . "{$_SERVER['REQUEST_URI']}\n" . "User-Agent: \"{$_SERVER['HTTP_USER_AGENT']}\"\n" . "Referrer URL: \"{$_SERVER['HTTP_REFERER']}\"\n" . "Exception:\n\n" . var_export($exception, true));
        }
    }
    $response = new APIResponse();
    $response->setVersion(0);
    $response->setError(new KurogoError($exception->getCode(), "Error", "An error has occurred"));
    $response->display();
}