Esempio n. 1
0
 /**
  * Singleton for database connections
  *
  * This method is going to verify if there's an existing instance
  * of a database object and if so will return it.
  *
  * @param  string $name The name of the instantiation (namespace emulation)
  *                      This parameter is optional and is defaulted to 'default'
  *
  * @return PDO A new PDO object or an existing PDO object
  */
 protected static function factory($name = 'default')
 {
     if (!isset(self::$instance[$name])) {
         $configs = Frapi_Internal::getCachedDbConfig();
         self::$instance[$name] = new PDO('mysql:dbname=' . $configs['db_database'] . ';host=' . $configs['db_hostname'], $configs['db_username'], $configs['db_password']);
     }
     return self::$instance[$name];
 }
Esempio n. 2
0
 /**
  * Tear Down - delete APC keys used in tests.
  *
  * @return void
  **/
 protected function tearDown()
 {
     $kvs = $this->keysValuesProvider();
     foreach ($kvs as $arr) {
         Frapi_Internal::deleteCached($arr[0]);
         //            apc_delete($arr[0]);
     }
 }
Esempio n. 3
0
 public function testIsPartnerExpectTrue()
 {
     $partner = array('*****@*****.**' => array('email' => '*****@*****.**', 'api_key' => 'e5b9e917648c57a978ba633095cb7a12fb0a647e'));
     Frapi_Internal::setCached('Partners.emails-keys', $partner);
     $partner = Frapi_Model_Partner::isPartner('*****@*****.**', 'e5b9e917648c57a978ba633095cb7a12fb0a647e');
     $this->assertTrue($partner);
     Frapi_Internal::deleteCached('Partners.emails-keys');
 }
Esempio n. 4
0
 /**
  * Singleton for database connections
  *
  * This method is going to verify if there's an existing instance
  * of a database object and if so will return it.
  *
  * @param  string $name The name of the instantiation (namespace emulation)
  *                      This parameter is optional and is defaulted to 'default'
  *
  * @return PDO A new PDO object or an existing PDO object
  */
 protected static function factory($name = 'default')
 {
     if (!isset(self::$instance[$name])) {
         $configs = Frapi_Internal::getCachedDbConfig();
         self::$instance[$name] = new PDO('mysql:dbname=' . $configs['db_database'] . ';host=' . $configs['db_hostname'], $configs['db_username'], $configs['db_password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
     }
     return self::$instance[$name];
 }
Esempio n. 5
0
 /**
  * This function is called from Frapi_Security::isPartner
  * so this function must actually implement the validation
  * of the partner.
  *
  * @param String $partnerID  Partner identifier (email).
  * @param String $partnerKey Partner key (sha1 hash).
  *
  * @return Boolean Whether the supplied partnerID and partnerKey are valid details.
  */
 public static function isPartner($partnerID, $partnerKey)
 {
     if (!($partners = Frapi_Internal::getCached("Partners.emails-keys"))) {
         $partners = Frapi_Internal::getCachedPartners();
     }
     if (isset($partners[$partnerID]) && $partners[$partnerID]['email'] == $partnerID && $partners[$partnerID]['api_key'] == $partnerKey) {
         return true;
     }
     return false;
 }
Esempio n. 6
0
 /**
  * Find out whether a username is a valid one or not.
  *
  * This method is used from the Digest to figure out whether or not a user
  * is a valid handle and one that should be used.
  *
  * @param string $partnerID  Partner identifier (email).
  *
  * @return mixed Information about a user or a Boolean Whether the 
  *               supplied partnerID are valid details.
  */
 public static function isPartnerHandle($partnerID)
 {
     if (!($partners = Frapi_Internal::getCached("Partners.emails-keys"))) {
         $partners = Frapi_Internal::getCachedPartners();
     }
     if (isset($partners[$partnerID]) && $partners[$partnerID]['email'] == $partnerID) {
         return $partners[$partnerID];
     }
     return false;
 }
Esempio n. 7
0
 private static function getDbConfig()
 {
     $configs = Frapi_Internal::getDB()->query($sql)->fetchAll();
     $conf = array();
     foreach ($configs as $key => $value) {
         $conf[$value['key']] = $value['value'];
     }
     unset($configs);
     unset($db);
     return $conf;
 }
Esempio n. 8
0
 /**
  * Singleton for database connections
  *
  * This method is going to verify if there's an existing instance
  * of a database object and if so will return it.
  *
  * @param  string $name The name of the instantiation (namespace emulation)
  *                      This parameter is optional and is defaulted to 'default'
  *
  * @return PDO A new PDO object or an existing PDO object
  */
 protected static function factory($name = 'default')
 {
     if (!isset(self::$instance[$name])) {
         $configs = Frapi_Internal::getCachedDbConfig();
         $dsn = self::buildDsn($configs);
         // I iz not happy with this. We already have a switch
         // for the dsn in the "buildDsn" method...
         if (isset($configs['db_engine']) && in_array($configs['db_engine'], array('pgsql'))) {
             // DSN that have the user/pass implicitely defined.
             self::$instance[$name] = new PDO($dsn);
         } else {
             // Other dsns like mysql, mssql, etc.
             self::$instance[$name] = new PDO($dsn, $configs['db_username'], $configs['db_password']);
         }
     }
     return self::$instance[$name];
 }
Esempio n. 9
0
 /**
  * Load routes from APC, database etc.
  * Prepare routes if necessary!
  *
  * @return void
  */
 public function loadAndPrepareRoutes()
 {
     if ($routes = Frapi_Internal::getCached('Router.routes-prepared')) {
         $this->setPreparedRoutes($routes);
     } else {
         $routes = array();
         $ret = Frapi_Internal::getConfiguration('actions');
         $rows = $ret->getAll('action');
         foreach ($rows as $row) {
             if (isset($row['route']) && !empty($row['route'])) {
                 $routes[$row['name']] = $row['route'];
             }
         }
         $this->setPreparedRoutes($preparedRoutes = self::prepareRoutes($routes));
         Frapi_Internal::setCached('Router.routes-prepared', $preparedRoutes);
     }
 }
Esempio n. 10
0
 /**
  * Send HTTP headers, namely HTTP Status Code.
  * We need the unformatted content to determine
  * what headers to send.
  *
  * @param Mixed $response
  *
  * @return Object $this
  **/
 public function sendHeaders($response)
 {
     header('HTTP/1.1 ' . intval($response->getStatusCode()));
     if ($response instanceof Frapi_Response) {
         $content_type = $response->getContentType();
         if ($content_type) {
             $this->mimeType = $content_type;
         }
     }
     header('Content-type: ' . $this->mimeType . '; charset=utf-8');
     //IF debugging is turned on, then send cache info
     //headers - very useful for seeing what's happening.
     if (Frapi_Controller_Main::MAIN_WEBSERVICE_DEBUG) {
         $log = Frapi_Internal::getLog();
         $cache_info = 'Cache Fetches(' . $log['cache-get']['times'] . ') ' . 'Cache Stores(' . $log['cache-set']['times'] . ') ' . 'DbHandles(' . $log['db']['times'] . ')';
         header('X-Cache-Info: ' . $cache_info);
         if (!empty($log['cache-get']['keys'])) {
             sort($log['cache-get']['keys']);
             header('X-Cache-Lookups: ' . implode(' ', $log['cache-get']['keys']));
         }
         if (!empty($log['cache-set']['keys'])) {
             sort($log['cache-set']['keys']);
             header('X-Cache-Stores: ' . implode(' ', $log['cache-set']['keys']));
         }
     }
     $cache = new Frapi_Internal();
     $cache = $cache->getCachedDbConfig();
     $allowCrossDomain = isset($cache['allow_cross_domain']) ? $cache['allow_cross_domain'] : false;
     if ($allowCrossDomain) {
         header('Access-Control-Allow-Origin: *');
         header('Access-Control-Allow-Headers: *');
         header('Access-Control-Allow-Credentials: true');
         header('Access-Control-Allow-Methods: POST,GET,PUT,DELETE,HEAD');
         header('Access-Control-Max-Age: 604800');
     }
     return $this;
 }
Esempio n. 11
0
 protected function _initApiUrl()
 {
     $int = Frapi_Internal::getCachedDbConfig();
     Frapi_Internal::$_hash = isset($int['api_url']) ? hash('sha1', $int['api_url']) : false;
 }
Esempio n. 12
0
 /**
  * Test Internal class can init DB.
  *
  **/
 public function testInitDB()
 {
     $db = Frapi_Internal::getDB();
     $this->assertTrue($db instanceof PDO);
 }
Esempio n. 13
0
 public static function getMimeTypeMap()
 {
     try {
         $cache = new Frapi_Internal();
         $mimetypes = $cache->getConfiguration('mimetypes')->getAll('mimetype');
         $map = array();
         foreach ($mimetypes as $mimetype) {
             $map[$mimetype['mimetype']] = $mimetype['output_format'];
         }
     } catch (Exception $e) {
         // No matter what happens for legacy reasons we fallback to the defaults
         return false;
     }
     return $map;
 }
Esempio n. 14
0
    /**
     * Save the new configuration
     *
     * This method saves the newly updated configuration. Please note
     * that at it's basic stage, the config files have a <config> root
     * node, however after saving using the Zend_Config_Writer_Xml, the
     * root node becomes <zend-config>.
     *
     * Don't worry about it, the parser won't see a difference.
     *
     * @throws Zend_Exception
     * @uses   Zend_Config_Writer_Xml
     * @return bool True of false whether the saving of the file worked or not.
     */
    protected function save()
    {
        $this->configIsWriteable();

        $helper = new Lupin_Config_Helper_XmlArray();

        Frapi_Internal::deleteCached('configFile-' . $this->configName);

        return $helper->write(
            array(
                'config'       => $this->config,
                'filename'     => $this->configFile,
                'topLevelName' => $this->configName,
            )
        );
    }
Esempio n. 15
0
 /**
  * Parse mimetype for params
  *
  * @param string $mimetype
  *
  * @return array
  */
 protected function parseMimeTypes()
 {
     $cache = new Frapi_Internal();
     $mimetypes = $cache->getConfiguration('mimetypes')->getAll('mimetype');
     $patterns = array();
     foreach ($mimetypes as $mimetype) {
         if (strpos($mimetype['mimetype'], ':') === false) {
             continue;
         }
         $segments = preg_split("@/|\\.|\\+@", $mimetype['mimetype']);
         $mimetype['mimetype'] = preg_quote($mimetype['mimetype']);
         foreach ($segments as $segment) {
             if ($segment[0] == ':') {
                 $param = substr($segment, 1);
                 $params[] = $param;
                 $mimetype['mimetype'] = str_replace(preg_quote($segment), '(?P<' . preg_quote($param) . '>.*?)', $mimetype['mimetype']);
             }
         }
         // Don't add mimetypes that didn't have params
         if (sizeof($params)) {
             $patterns[] = $mimetype + array('pattern' => "@^{$mimetype['mimetype']}\$@", 'params' => $params);
         }
     }
     return $patterns;
 }
Esempio n. 16
0
 /**
  * Check if it is a public action or not.
  *
  * @param  string  $action The action
  * @return bool    If it's a valid action or not.
  */
 public static function isPublicAction($action)
 {
     $actions = Frapi_Internal::getCachedActions('public');
     if (is_array($actions) && !in_array($action, $actions)) {
         return false;
     }
     return true;
 }
Esempio n. 17
0
 public static function getMimeTypeMap()
 {
     try {
         $cache = new Frapi_Internal();
         $mimetypes = $cache->getConfiguration('mimetypes')->getAll('mimetype');
         $outputs = $cache->getConfiguration('outputs')->getAll('output');
         $disabled = array();
         foreach ($outputs as $output) {
             if ($output['enabled'] == 0) {
                 $disabled[strtolower($output['name'])] = true;
             }
         }
         $map = array();
         foreach ($mimetypes as $mimetype) {
             if (isset($disabled[strtolower($mimetype['output_format'])])) {
                 continue;
             }
             $map[$mimetype['mimetype']] = $mimetype['output_format'];
         }
     } catch (Exception $e) {
         // No matter what happens for legacy reasons we fallback to the defaults
         return false;
     }
     return $map;
 }
Esempio n. 18
0
    /**
     * Get errors from database.
     *
     * This method fetches the errors from the database (XML)
     * key-values which then get cached when used in self::_get
     *
     * @return Array An array of errors
     */
    private static function _getErrorsFromDb()
    {
        $conf          = Frapi_Internal::getConfiguration('errors');

        $conf_errors   = $conf->getAll('error');

        $errors = array();

        if (is_array($conf_errors) && !empty($conf_errors)) {
            foreach ($conf_errors as $errKey => $error) {
                $errors[$error['name']] = $error;
            }
        }

        return $errors;
    }
Esempio n. 19
0
    /**
     * Send HTTP headers, namely HTTP Status Code.
     * We need the unformatted content to determine
     * what headers to send.
     *
     * @param Mixed $response
     *
     * @return Object $this
     **/
    public function sendHeaders($response)
    {
        header('HTTP/1.1 '.intval($response->getStatusCode()));

        if ($response instanceof Frapi_Response) {
            $content_type = $response->getContentType();
            if ($content_type) {
                $this->mimeType = $content_type;
            }
        }

        header('Content-type: '.$this->mimeType.'; charset=utf-8');

        //IF debugging is turned on, then send cache info
        //headers - very useful for seeing what's happening.
        if (Frapi_Controller_Main::MAIN_WEBSERVICE_DEBUG) {
            $log = Frapi_Internal::getLog();

            $cache_info = 'Cache Fetches(' . $log['cache-get']['times'] . ') ' .
                          'Cache Stores(' . $log['cache-set']['times'] . ') ' .
                          'DbHandles(' . $log['db']['times'] . ')';

            header('X-Cache-Info: '.$cache_info);

            if (!empty($log['cache-get']['keys'])) {
                sort($log['cache-get']['keys']);
                header('X-Cache-Lookups: '.implode(' ', $log['cache-get']['keys']));
            }

            if (!empty($log['cache-set']['keys'])) {
                sort($log['cache-set']['keys']);
                header('X-Cache-Stores: '.implode(' ', $log['cache-set']['keys']));
            }
        }

        return $this;
    }
Esempio n. 20
0
 public function setUp()
 {
     Frapi_Internal::setCached('Output.mimeMaps', array('application/xml' => 'xml', 'text/xml' => 'xml', 'application/json' => 'json', 'text/json' => 'json', 'text/html' => 'html', 'text/plain' => 'json', 'application/javascript' => 'js', 'text/javascript' => 'js', 'text/php-printr' => 'printr', 'application/vnd.test.:format' => ':format', 'application/vnd.test.:version.:format' => ':format', 'application/vnd.test.:version+json' => 'json', 'text/csv' => 'csv'));
 }
Esempio n. 21
0
 public static function getEnabledFormats()
 {
     try {
         if ($formats = Frapi_Internal::getCached('Output.formats-enabled')) {
             return $formats;
         }
         $cache = new Frapi_Internal();
         $outputs = $cache->getConfiguration('outputs')->getAll('output');
         $formats = array();
         foreach ($outputs as $output) {
             if ($output['enabled'] == 1) {
                 $formats[] = strtolower($output['name']);
             }
         }
     } catch (Exception $e) {
         return false;
     }
     Frapi_Internal::setCached('Output.formats-enabled', $formats);
     return $formats;
 }
Esempio n. 22
0
 /**
  * Delete key from cache(s).
  *
  * This method deletes a key from the cache instance.
  *
  * @param  string  The cached key to delete.
  * @return void
  */
 public static function deleteCached($key)
 {
     self::log('cache-delete', $key);
     $hash = self::getHash();
     if (!isset(self::$cache)) {
         self::$cache = Frapi_Cache::getInstance(FRAPI_CACHE_ADAPTER);
     }
     return self::$cache->delete($hash . '-' . $key);
 }
Esempio n. 23
0
File: Main.php Progetto: helgi/frapi
 /**
  * Get default format from SQLite database
  *
  * A format (output type) has not been supplied
  * so try to get default from backend.
  *
  * @return String The format.
  */
 public function getDefaultFormatFromConfiguration()
 {
     if ($default_output_format = Frapi_Internal::getCached('Output.default-format')) {
         return $default_output_format;
     }
     $conf = Frapi_Internal::getConfiguration('outputs');
     $row = $conf->getByField('output', 'default', '1');
     if (isset($row) && isset($row['name'])) {
         Frapi_Internal::setCached('Output.default-format', $row['name']);
         return $row['name'];
     }
     return Frapi_Controller_Api::DEFAULT_OUTPUT_FORMAT;
 }
Esempio n. 24
0
File: XML.php Progetto: Rud5G/frapi
 /**
  * Populate the Output
  *
  * This method populates the $this->response
  * variable with the value returned from the
  * action.
  *
  * @param Mixed  $response Most of the times an array but could be and stdClass
  * @param String $customTemplate The custom template file to use instead of the default one.
  *
  * @return Object $This object
  */
 public function populateOutput($data, $customTemplate = false)
 {
     $directory = CUSTOM_OUTPUT . DIRECTORY_SEPARATOR . 'xml';
     $file = $directory . DIRECTORY_SEPARATOR . ucfirst(strtolower($this->action)) . '.xml.tpl';
     if ($customTemplate !== false) {
         $file = $directory . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . $customTemplate . '.xml.tpl';
     }
     $xml = '';
     if (!is_array($data)) {
         $data = $this->_normalizeToArray($data);
     }
     $print = hash('md5', json_encode($data + array('__action__name' => $this->action)));
     if ($response = Frapi_Internal::getCached($print)) {
         $this->response = json_decode($response);
     } elseif (file_exists($file)) {
         ob_start();
         echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
         include $file;
         $xml = ob_get_contents();
         ob_end_clean();
         $this->response = $xml;
         Frapi_Internal::setCached($print, json_encode($xml));
     } elseif ($this->action == 'defaultError') {
         $directory = LIBRARY_OUTPUT . DIRECTORY_SEPARATOR . 'xml';
         $file = $directory . DIRECTORY_SEPARATOR . 'Defaulterror.xml.tpl';
         ob_start();
         echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
         include $file;
         $xml = ob_get_contents();
         ob_end_clean();
         $this->response = $xml;
         Frapi_Internal::setCached($print, json_encode($xml));
     } else {
         $this->response = $this->_generateXML($data);
     }
     return $this;
 }
Esempio n. 25
0
 /**
  * Parse mimetype for params
  *
  * @param string $mimetype
  *
  * @return array
  */
 protected function parseMimeTypes()
 {
     $cache = new Frapi_Internal();
     $mimetypes = $cache->getConfiguration('mimetypes')->getAll('mimetype');
     if (!$mimetypes) {
         return array();
     }
     $patterns = array();
     foreach ($mimetypes as $mimetype) {
         $this->mimeMaps[$mimetype['mimetype']] = $mimetype['output_format'];
         if (strpos($mimetype['mimetype'], ':') === false) {
             continue;
         }
         $segments = preg_split("@/|\\.|\\+@", $mimetype['mimetype']);
         $mimetype['pattern'] = preg_quote($mimetype['mimetype']);
         $params = array();
         foreach ($segments as $segment) {
             if ($segment[0] == ':') {
                 $param = substr($segment, 1);
                 $params[] = $param;
                 $mimetype['pattern'] = str_replace(preg_quote($segment), '(?P<' . preg_quote($param) . '>[^\\.\\+]*?)', $mimetype['pattern']);
             }
         }
         $mimetype['pattern'] = '@^' . $mimetype['pattern'] . '$@';
         // Don't add mimetypes that didn't have params
         if (sizeof($params)) {
             $patterns[] = $mimetype + array('params' => $params);
         }
     }
     return $patterns;
 }
Esempio n. 26
0
 /**
  * Get a hash of your server
  * 
  * If you happen to have multiple installations of frapi
  * you would get apc cache collisions if we woulnd't have
  * some sort of hashing and identification of the hostnames.
  *
  * Right now this hash is very rudimentary, it's simply and sha1
  * hash of the HTTP_HOST that you are serving frapi from.
  *
  * @return string self::$_hash The sha1-server hash
  */
 public static function getHash()
 {
     if (self::$_hash) {
         return self::$_hash;
     }
     self::$_hash = hash('sha1', $_SERVER['HTTP_HOST']);
     return self::$_hash;
 }