예제 #1
0
파일: db.php 프로젝트: Tapac/hotscot
 public static function createConnection($db)
 {
     // get the configuration
     $config = getConfiguration('db', $db);
     // create mysqli connection
     return new mysqli(array_val($config, 'server'), array_val($config, 'username'), array_val($config, 'password'), array_val($config, 'database'), array_val($config, 'port'));
 }
예제 #2
0
파일: sprite.php 프로젝트: Tapac/hotscot
 /**
  * the constructor takes the folder name containing the images and an optional parameter to change the output file type
  *
  * @param string $name 
  * @param string $type 
  * @author Craig Ulliott
  */
 function __construct($name, $type = 'png')
 {
     // apply any overides to the configuration
     $config = getConfiguration('sprite');
     $this->base_path = array_val($config, 'base_path', $this->base_path);
     // is it a relative path or not
     if (substr($this->base_path, 1, 1) != '/') {
         $this->base_path = SITE_ROOT . $this->base_path;
     }
     $this->extensions = array_val($config, 'extensions', $this->extensions);
     $this->base_url = array_val($config, 'base_url', $this->base_url);
     // sanity check the name of the image
     if (preg_match("/^([a-z])+\$/", $name)) {
         $this->name = $name;
     } else {
         throw new Exception("not a valid folder name, should be a-z, all lower case with no spaces");
     }
     // check this is one of the extensions we are allowing
     if (in_array($type, $this->extensions)) {
         $this->type = $type;
     } else {
         throw new Exception("not a valid image type");
     }
     // add all images in the given directory
     $this->addDirectory($this->base_path . '/' . $name);
 }
예제 #3
0
파일: cache.php 프로젝트: Tapac/hotscot
 static function getCache()
 {
     if (!self::$cache) {
         $config = getConfiguration('cache');
         // apply any overides to the configuration
         self::$compression = array_val($config, 'compression', self::$compression);
         self::$default_ttl = array_val($config, 'default_ttl', self::$default_ttl);
         self::$connect_timeout_msec = array_val($config, 'connect_timeout_msec', self::$connect_timeout_msec);
         self::$cache_enabled = array_val($config, 'cache_enabled', self::$cache_enabled);
         self::$local_cache_enabled = array_val($config, 'local_cache_enabled', self::$local_cache_enabled);
         // apply any overides to the debug mode
         self::$debug = array_val($config, 'debug', self::$debug);
         self::$local_cache_debug = array_val($config, 'local_cache_debug', self::$local_cache_debug);
         // build the cache object and connect the servers
         self::$cache = new Memcache();
         // get the server list out of the configuration
         foreach (array_val($config, 'servers') as $machine_name) {
             // load the configuration block for each server
             $server_config = getConfiguration('cache', $machine_name);
             // setup this servers connection
             self::$cache->addServer($server_config['host'], $server_config['port'], false, $server_config['weight'], 1, 1, false, null);
             //, self::$connect_timeout_msec);
         }
     }
     return self::$cache;
 }
예제 #4
0
 /**
  * test the configuration loads correctly for each configuration file
  */
 public function testConfiguration()
 {
     // get the database configuration
     $config = getConfiguration('db');
     // check we get the main database configuration
     $this->assertArrayHasKey('db1', $config);
     // check the database configuraion has all the required variables
     $this->assertArrayHasKeys($this->expectedDatabaseFields, $config['db1']);
     // check use of the second parameter to target specific sections works as intended
     $config = getConfiguration('db', 'db1');
     $this->assertArrayHasKeys($this->expectedDatabaseFields, $config);
     // get the cache configuration
     $config = getConfiguration('cache');
     // check we get the main database configuration
     $this->assertArrayCountGreaterThanOrEqual($config, 1);
     // check we get back a list of servers
     $server_list = array_val($config, 'servers');
     $this->assertArrayCountGreaterThanOrEqual($server_list, 1);
     // check we get back the host and port variables for each server
     foreach ($server_list as $server_name) {
         $server_config = array_val($config, $server_name);
         $this->assertArrayHasKeys($this->expectedCacheFields, $server_config);
     }
     // get the ab test configuration
     // ab tests are optional, only test the output if we have some
     if ($config = getConfiguration('ab_test')) {
         //test names
         foreach ($config as $test_name => $test_details) {
             // check the test name is valid
             $this->assertRegExp('/^[a-zA-Z0-9]{4}$/', $test_name);
         }
     }
 }
예제 #5
0
파일: request.php 프로젝트: Tapac/hotscot
/**
 * adds params on to an existing query string
 *
 * @param string $url 
 * @param array $additional_params 
 * @return string
 * @author Craig Ulliott
 */
function http_add_params($url, $additional_params)
{
    // break apart the original url
    $url_r = parse_url($url);
    // parse and combine two query strings
    $new_query_string = qs(array_val($url_r, 'query', ''), $additional_params);
    return (isset($url_r['scheme']) ? $url_r['scheme'] . '://' : '') . (isset($url_r['user']) ? $url_r['user'] . (isset($url_r['pass']) ? ':' . $url_r['pass'] : '') . '@' : '') . (isset($url_r['host']) ? $url_r['host'] : '') . (isset($url_r['port']) ? ':' . $url_r['port'] : '') . (isset($url_r['path']) ? $url_r['path'] : '') . '?' . $new_query_string . (isset($url_r['fragment']) ? '#' . $url_r['fragment'] : '');
}
예제 #6
0
 /** 
  * assert our entry was logged
  * 
  * @depends testLogSomething
  */
 public function testLogGetLastQueries()
 {
     // the last query should be the one we did in the testLogSomething test
     $entry = Log::getLastQueries('database');
     // did this entry come back
     $this->assertEquals(array_val($entry, array(0, 0)), 'test query');
     $this->assertEquals(array_val($entry, array(0, 1)), 4);
 }
예제 #7
0
function request_($override = array())
{
    static $request;
    if (!isset($request) or !empty($override)) {
        $request = array('method' => array_val($override, 'method', strtoupper(server_var('REQUEST_METHOD'))), 'path' => array_val($override, 'path', rawurldecode('/' . ltrim(webserver_specific('request_path'), '/'))), 'query' => array_val($override, 'query', $_GET), 'form' => array_val($override, 'form', $_POST), 'server_vars' => array_val($override, 'server_vars', $_SERVER), 'headers' => array_val($override, 'headers', webserver_specific('request_headers')), 'body' => array_val($override, 'body', valid_body_(file_get_contents('php://input'))));
    }
    return $request;
}
예제 #8
0
 /**
  * catch all methods for the autocomplete and pass them to this controller
  *
  * @param string $method 
  * @param array $params 
  * @return void
  * @author Craig Ulliott
  */
 public function catch_all($method, array $params)
 {
     $query = array_val($params, 'q');
     $results = WIB::getClient()->call_method('autocomplete.' . $method, array('q' => $query));
     // normalize to minute
     $data = array();
     foreach ($results['results'] as $result) {
         $data[] = array($result['type'] . ':' . $result['id'] => $result['name']);
     }
     v('json/data', $data);
 }
예제 #9
0
파일: planet.php 프로젝트: Tapac/hotscot
 public function save_planet(array $params)
 {
     $name = array_val_required($params, 'name');
     // are we editing an existing planet
     if ($planetID = array_val($params, 'planetID')) {
         $planet = m('Planet', $planetID);
     } else {
         $planet = m('Planet');
     }
     $planet->set_name($name);
     $planet->save();
     v('json/success', 'Planet saved');
 }
예제 #10
0
 public function save_inhabitant(array $params)
 {
     $name = array_val_required($params, 'name');
     $planetID = array_val_required($params, 'planetID');
     // the planet this inhabitant is on
     $planet = m('Planet', $planetID);
     // are we editing an existing inhabitant
     if ($inhabitantID = array_val($params, 'inhabitantID')) {
         $inhabitant = m('inhabitant', $inhabitantID);
     } else {
         $inhabitant = m('inhabitant');
     }
     $inhabitant->set_name($name);
     $inhabitant->set_planet($planet);
     $inhabitant->save();
     v('json/success', 'Inhabitant saved');
 }
예제 #11
0
 /**
  * jsondecode an array from an array value
  */
 public function testarray_val_json()
 {
     // some json to test against
     $json = json_encode(array('foo' => 'bar'));
     $array = array('arr' => $json);
     // target the velue in the array
     $v = array_val_json($array, 'arr');
     // assert the array looks as expected
     $this->assertTrue(array_val($v, 'foo') === 'bar');
     // for the array key doesnt exist
     $v = array_val_json($array, 'invalid');
     // assert there was an empty array returned
     $this->assertTrue(is_array($v) && empty($v));
     // for the array key doesnt exist, but a default is used
     $v = array_val_json($array, 'invalid', array('a' => 'b'));
     // assert there was an empty array returned
     $this->assertTrue(array_val($v, 'a') === 'b');
 }
예제 #12
0
function combine_and_upload($id)
{
    $files = array();
    $photo_count = $_SESSION['photo_number_' . $id];
    for ($i = 1; $i <= $photo_count; $i++) {
        $files[] = PHOTO_PATH . $id . '_' . $i . '.jpeg';
    }
    // combine photos into one file and upload
    if ($combined_file = combine_photos($files)) {
        $result = upload_photo($combined_file);
        $facebook_id = array_val($result, 'id');
        if (empty($facebook_id)) {
            error_log('Failed to upload to Facebook: ' . print_r($result, 1));
        }
        // send the combined file back to the client regardless of success
        echo json_encode(array('photo_src' => PUBLIC_PHOTO_PATH . basename($combined_file), 'facebook_id' => $facebook_id));
        if (THE_B0XX_URL) {
            notify_the_b0xx($facebook_id);
        }
        // "Uploaded photo: http://www.facebook.com/photo.php?fbid={$result['id']}\n";
    }
}
예제 #13
0
/**
 * loads a configuration file from the system, if the optional process_sections
 * parameter is used then the configuration is broken into sections coresponding 
 * to headers in the configuration file [headers look like this]
 *
 * @param string $section 
 * @param bool $process_sections 
 * @return void
 * @author Craig Ulliott
 */
function getConfiguration($file, $section = null)
{
    // a key to use for setting and getting this from the cache
    $key = 'configuration_' . $file . '_' . $section;
    // try APC first
    if (!($configuration = apc_fetch($key))) {
        $configuration_file = CONFIGURATION_PATH . $file . '.ini';
        // ensure the configuration file exists
        if (file_exists($configuration_file)) {
            //build an associative array from this configuration file
            $configuration = parse_ini_file($configuration_file, true);
            //add to the cache for next time
            apc_add($key, $configuration);
        } else {
            trigger_error('configuration file for ' . $section . ' does not exist', E_USER_ERROR);
        }
    }
    // are we returning just one section
    if ($section) {
        return array_val($configuration, $section);
    }
    // pass back the configuration associative array
    return $configuration;
}
예제 #14
0
파일: wib.php 프로젝트: Tapac/hotscot
/**
 * call the WIB API and convert urls into trackable urls
 *
 * @param mixed $urls 
 * @return void
 * @author Craig Ulliott
 */
function track_urls($urls, $additional_params = null)
{
    // to make the code easier, and accept one or an array of urls
    if (!is_array($urls)) {
        $urls = array($urls);
        $return_single = true;
    } else {
        $return_single = false;
    }
    // save on bandwidth
    $unique_urls = array_unique($urls);
    // here we add any new params we want to the url
    if ($additional_params) {
        foreach ($unique_urls as $k => $url) {
            // we cant add params to some urls
            if (!stristr($url, 'ad.doubleclick.net')) {
                $unique_urls[$k] = http_add_params($url, $additional_params);
            }
        }
    }
    // build an assoc array to return the new urls
    $new_urls = array();
    // build cache keys
    $cache_keys = array();
    foreach ($unique_urls as $url) {
        $cache_keys[] = 'track_urls_' . $url;
    }
    // try the cache first
    foreach (Cache::get($cache_keys) as $cache_key => $lilurl) {
        $url = substr($cache_key, 11);
        // add to the new url list
        $new_urls[$url] = $lilurl;
        // remove from the $unique_urls queue
        $k = array_search($url, $unique_urls);
        if ($k !== false) {
            unset($unique_urls[$k]);
        }
    }
    // we want to get all the remaining lilurls in one call
    WIB::getClient()->start_batch();
    // loop through each
    foreach ($unique_urls as $url) {
        // if we didnt get it from the cache
        if (!array_key_exists($url, $new_urls)) {
            $response = WIB::getClient()->call_method('lilurl.create', array('url' => $url));
        }
    }
    // get the results
    $results = WIB::getClient()->run_batch();
    // get only the parts we want from each URL
    foreach ($results as $result) {
        //the url we passed to the wib api
        $tracked_url = array_val($result, array('results', 0, 'url'));
        // we now go back to the very original $urls array, as we dont want to pass back the "additional params"
        $k = array_search($tracked_url, $unique_urls);
        $original_url = $urls[$k];
        $tracking_url = array_val($result, array('results', 0, 'lilurl'));
        if ($original_url && $tracking_url) {
            // add it to the result
            $new_urls[$original_url] = $tracking_url;
            // cache it for next time
            $from_cache = Cache::add('track_urls_' . $original_url, $tracking_url);
        }
    }
    if ($return_single) {
        return reset($new_urls);
    }
    return $new_urls;
}
예제 #15
0
/**
 * Tests if 'we are' currently handling an ajax request
 * 
 * This is done by checking the `$_SERVER` variable and the request_id.
 * We set the request_id in plain requests in the SESSION and add it to AJAX requests so we can compare those two here.
 * @return bool true or false
 */
function system_is_ajax_call()
{
    if (!isset($GLOBALS['result_of_system_is_ajax_call'])) {
        $GLOBALS['result_of_system_is_ajax_call'] = strtolower(array_val($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
        if (!$GLOBALS['result_of_system_is_ajax_call']) {
            $GLOBALS['result_of_system_is_ajax_call'] = isset($_REQUEST['request_id']) && isset($_SESSION['request_id']) && $_REQUEST['request_id'] == $_SESSION['request_id'];
        }
    }
    return $GLOBALS['result_of_system_is_ajax_call'];
}
예제 #16
0
파일: index.php 프로젝트: Tapac/hotscot
    // tell wib client who the active user is
    WIB::setSessionUser($user);
} else {
    define('CURRENT_UID', NULL);
    define('CURRENT_SESSION_KEY', NULL);
}
/**
 * the HTTP/HTML Template Handler & Presentation Layer (the view in mvc)
 */
require 'view.php';
// we are serving templates out of this folder
Template::setTemplatePath(CORE_PATH . 'view/');
// we are serving templates out of this folder
Template::setLayoutPath(SITE_ROOT . 'htdoc/layout/');
// the uri to target the controller
$controller = array_val($_REQUEST, 'controller');
// lots of people are going to hate this but i want to enforce denying access to global variables
// if we enforce use of $params, it makes is much easier to write tests, and create code which scales
$params = $_REQUEST;
$_REQUEST = $_GET = $_POST = array();
// the controller to dispatch is determined by the controller $_REQUEST variable
// the parameters to pass in are from the http request
// and we are using the HTTP/HTML View
try {
    //
    dispatch_controller($controller, $params, $user);
} catch (Exception $e) {
    // send the error to the error controller with the generated message
    $controller_obj = c('error');
    // a useful message in dev, or a safe message for production
    if (ENV == 'dev') {
예제 #17
0
<?php

require 'header.php';
$action = array_val($_GET, 'action');
switch ($action) {
    case 'take_photo':
        echo take_photo($_GET['id'], $_GET['photos_to_take']);
        break;
    case 'combine_and_upload':
        echo combine_and_upload($_GET['id']);
        exit;
    default:
        $strips = array();
        $files = scandir(PHOTO_PATH, 1);
        foreach ($files as $file) {
            if (preg_match('/^combined_(.*)\\.(jpg|jpeg)$/', $file)) {
                $strips[] = 'photos/' . $file;
            }
        }
        // try to keep the page from becoming impossible to load
        $strips = array_slice($strips, 0, 50);
        require APP_ROOT . 'themes/' . THEME . '/index.htm';
}
예제 #18
0
파일: header.php 프로젝트: Tapac/hotscot
require_once CORE_PATH . 'client/facebook/facebook_wrapper.php';
require_once CORE_PATH . 'client/wib/whereivebeen_wrapper.php';
// ------------------------------------------------------
// system configuration
require_once CORE_PATH . 'config.php';
// ------------------------------------------------------
// make cookies work in IE iframes
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
// if we're in dev, enable all query logs
if (ENV == 'dev' || array_val($_REQUEST, 'mongoose7')) {
    Log::enableAll();
}
// all users get a php session. we have our own session handler which uses the database
session_set_save_handler(array('Session', 'open'), array('Session', 'close'), array('Session', 'read'), array('Session', 'write'), array('Session', 'destroy'), array('Session', 'gc'));
session_start();
// are we overriding the test with a request variable
if ($current_test = array_val($_REQUEST, 'AB_USER_TEST')) {
    // save this for the duration of the users session
    $_SESSION['AB_USER_TEST'] = $current_test;
} else {
    // try and pull it from the session
    if (!($current_test = array_val($_SESSION, 'AB_USER_TEST'))) {
        // we dont have one in the session then assign a new one
        $current_test = ABTest::getRandomTest();
        $_SESSION['AB_USER_TEST'] = $current_test;
    }
}
// pass this to the AB framework, the framework will show content for this test only
ABTest::assignTest($current_test);
// load the configuration for simpledb
SimpleDB::loadConfiguration();
예제 #19
0
파일: view.php 프로젝트: Tapac/hotscot
 /**
  * this is the main feature of the view, in the MVC paradigm the controller sends updates to the view, this is 
  * the method which captures the updates.  
  * 
  * The uri is essentially the part of the system which we are updating so different output will be negotiated 
  * depending on the value of the uri.  
  * 
  * The data are the things which have changed due to the controller. 
  * 
  * The message is optional, it is for notes, debug information or with json sending messages back alongside the data
  *
  * @param string $uri 
  * @param array $data 
  * @return void
  * @author Craig Ulliott
  */
 public static function update($uri, $data = NULL)
 {
     // extract the base from the url, we use this to determine the type of output
     $uri_r = explode('/', trim($uri, '/'), 2);
     $base = array_val($uri_r, 0);
     $path = array_val($uri_r, 1);
     // for an error we try and determine the best format to send back the message
     if ($base == 'error') {
         // if the original request came from AJAX
         if (array_val($_SERVER, 'HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest') {
             // rewrite and use the json handler for this error
             $base = 'json';
             $path = 'fail';
             $data = array_val($data, 'message', 'Unknown Error');
         } else {
             // pass back the appropriate http code for this error
             $code = array_val($data, 'code');
             switch ($code) {
                 case '404':
                     header("HTTP/1.0 404 Not Found");
                     break;
                 case '500':
                     header("HTTP/1.0 500 Internal Server Error");
                     break;
                 default:
                     die('unknown error code "' . $code . '"');
             }
             // use the page handler to display this error
             $base = 'page';
             $path = 'error/' . $code;
         }
     }
     // for an error, we try to determine if we are
     // we handle the update differently depending on the base of the uri
     switch ($base) {
         // these are the different layout files, we are loading a whole page template and passing the result into these layouts
         case 'page':
             // we are preparing a full html page
             $tpl_vars = array();
             // the part of the page being updated from teh controller (aka the page contents)
             $tpl_vars['page_content'] = Template::loadTemplate($path, $data);
             // script and css clien side includes
             $tpl_vars['css_url'] = ENV == 'dev' ? '/css/generate' : STATIC_BASE_URL . 'css/style.css';
             $tpl_vars['js_url'] = ENV == 'dev' ? '/js/generate' : STATIC_BASE_URL . 'js/script.js';
             // todo::
             $tpl_vars['css_url'] = '/css/generate';
             $tpl_vars['js_url'] = '/js/generate';
             // the facebook API key
             $tpl_vars['fb_api_key'] = getConfiguration('facebook', 'api_key');
             // user values
             $tpl_vars['current_uid'] = CURRENT_UID;
             $tpl_vars['current_session_key'] = CURRENT_SESSION_KEY;
             // the parts of the path
             $path_r = explode('/', $path);
             // the active section is the first part of the path
             $active_section = reset($path_r);
             // used to set an active class on the main tab
             $tpl_vars['active'] = $active_section;
             // we build body classes to target css more accurately, one whole class for each parent section
             $body_classes = array();
             while ($path_r) {
                 $body_classes[] = implode('-', $path_r);
                 array_pop($path_r);
             }
             // the current login state
             if (CURRENT_UID) {
                 $body_classes[] = 'logged-in';
             }
             // the current browser (TODO:)
             if (true == false) {
                 $body_classes[] = 'ie-7';
             }
             // the body classes, used to determine the browser and login state
             $tpl_vars['body_class'] = implode(' ', $body_classes);
             // render the full page in either the base or admin layout file
             $output = Template::loadLayout($base, $tpl_vars);
             // complete the translations
             Translator::translate('en');
             $output = Translator::parse($output);
             // useful headers for debugging
             self::outputDebugHeaders();
             // output to the browser
             die($output);
             // partial means we are rendering a template (usualy html) but not passing it back into the page template
             // this is usually for partial page updates preformed by javascript
         // partial means we are rendering a template (usualy html) but not passing it back into the page template
         // this is usually for partial page updates preformed by javascript
         case 'partial':
             // render the template and output to the browser
             $output = Template::loadTemplate($path, $data);
             // complete the translations
             Translator::translate('en');
             $translated_output = Translator::parse($output);
             // useful headers for debugging
             self::outputDebugHeaders();
             // to hold the output
             $r = array();
             // the rest of the params go into the data key
             $r['page'] = $translated_output;
             // the correct content type
             header('Content-type: application/json');
             // build and send the json back to the browser
             $encoded_output = json_encode($r);
             die($encoded_output);
             // json is used by javascript for various AJAX functionality
         // json is used by javascript for various AJAX functionality
         case 'json':
             $r = array();
             switch ($path) {
                 // ouput raw json data
                 case 'data':
                     // the content type
                     header('Content-type: application/json');
                     // build and send the json back to the browser
                     $encoded_output = json_encode($data);
                     die($encoded_output);
                     // success means we simply set the success key to 1, javascript will capture this
                 // success means we simply set the success key to 1, javascript will capture this
                 case 'success':
                     $r['success'] = 1;
                     break;
                     // fail means we simply set the success key to 0, javascript will capture this and handle is as a fail
                 // fail means we simply set the success key to 0, javascript will capture this and handle is as a fail
                 case 'fail':
                     $r['success'] = 0;
                     break;
                 default:
                     throw new exception($path . ' is not a valid path for json output');
             }
             // the data variable is used for sending back a message
             // it is sent as a blank string if one wasnt provided
             $r['message'] = (string) $data;
             // the correct content type
             header('Content-type: application/json');
             // build and send the json back to the browser
             $encoded_output = json_encode($r);
             die($encoded_output);
             // content pass through, with the uri as a content type
         // content pass through, with the uri as a content type
         case 'content':
             // the different content types we accept
             switch ($path) {
                 // common image types
                 case 'image/png':
                 case 'image/gif':
                 case 'image/jpeg':
                     // css and js
                 // css and js
                 case 'text/css':
                 case 'text/javascript':
                 case 'text/html':
                     // data
                 // data
                 case 'text/csv':
                     // the content type
                     header('Content-type: ' . $path);
                     // other useful headers for debugging
                     self::outputDebugHeaders();
                     // send to the browser
                     die($data);
                 default:
                     throw new exception($path . ' is not a known safe content type');
             }
         default:
             throw new exception($base . ' is not a valid base for updating this view');
     }
 }
예제 #20
0
파일: user.php 프로젝트: Tapac/hotscot
 public function get_data($params)
 {
     // the user
     if (!($user = $this->getUser())) {
         //we require a user to call facebook
         v('json/fail', 'user is required');
     }
     // fields to get. flip the array so we can use isset, which is way faster than in_array
     $fields = array_flip(array_val_csv($params, 'wib_fields'));
     // get profile data
     $profile_data = FB::getProfile($user);
     // this holds our output
     $data = array();
     // get name if requested
     if (isset($fields['name'])) {
         $data['name'] = trim(array_val($profile_data, 'name'));
     }
     // get gender
     if (isset($fields['gender'])) {
         $data['gender'] = low(array_val($profile_data, 'sex'));
     }
     // birthday
     if (isset($fields['birthday'])) {
         $data['birthday'] = $profile_data['birthday'] ? $profile_data['birthday'] : null;
     }
     // about me
     if (isset($fields['about_me'])) {
         $data['about_me'] = array_val($profile_data, 'about_me');
     }
     // photo url
     if (isset($fields['photo_url'])) {
         $data['photo_url'] = array_val($profile_data, 'pic_big');
     }
     // status
     if (isset($fields['status'])) {
         $data['status'] = array_val($profile_data, array('status', 'message'));
     }
     // status
     if (isset($fields['about_me'])) {
         $data['about_me'] = array_val($profile_data, 'interests');
     }
     // friends require another API call and a bit more work
     if (isset($fields['friends'])) {
         $friends = array();
         foreach (FB::getFriendIDs($user) as $id) {
             $friends[] = 'user:'******'friends'] = $friends;
     }
     // photos
     if (isset($fields['photos'])) {
         $data['photos'] = FB::getPhotos($user);
     }
     // albums
     if (isset($fields['albums'])) {
         $data['albums'] = FB::getAlbums($user);
     }
     // output JSON-encoded data
     v('json/data', $data);
 }
예제 #21
0
파일: array.php 프로젝트: Tapac/hotscot
/**
 * a function to wrap common functionality of getting an uploaded image (same as uploaded_file but has meta data)
 *
 * @author Craig Ulliott
 */
function uploaded_image($key)
{
    $r = array();
    // return image data and mime type
    if ($tmp_file = array_val($_FILES, array($key, 'tmp_name'))) {
        if (is_uploaded_file($tmp_file)) {
            $r['data'] = file_get_contents($tmp_file);
            $r['mime_type'] = image_type_to_mime_type(exif_imagetype($tmp_file));
        }
    }
    return $r;
}
예제 #22
0
파일: DBLibTest.php 프로젝트: Tapac/hotscot
 /**
  * getArray should return an array containing the same single row returned above
  * 
  * @depends testInsert
  */
 public function testGetArray()
 {
     // a query that should probably always work
     $result = DB::getArray('select * from `' . $this->db_name . '`.`' . $this->table_name . '`');
     // look for the text value we inserted earlier
     $this->assertEquals(array_val($result, array(0, 'foobar')), 'some text');
 }
예제 #23
0
파일: model.php 프로젝트: Tapac/hotscot
 /**
  * dynamic get and set methods for all 'fields' in wib objects, it is importaint that these methods are NOT case sensitive
  *
  * @return mixed
  * @author Craig Ulliott
  */
 function __call($name, $arguments)
 {
     // delete, get or set
     $action = strtolower(substr($name, 0, 4));
     // so we can work in a case insensitive way, we convert everything to lowercase
     $requested_field = strtolower(substr($name, 4));
     // is it the common 'added' value
     if ($requested_field == 'added') {
         $passing_model = false;
         $variable_name = 'added';
     } else {
         if ($variable_name = array_val($this->fields_lowercase, $requested_field)) {
             $passing_model = false;
         } else {
             // with the id appended to the requested_field
             if ($variable_name = array_val($this->fields_lowercase, $requested_field . 'id')) {
                 $passing_model = true;
             } else {
                 throw new ModelException('calling method ' . $name . ' on a model which doesnt have a field with that name');
             }
         }
     }
     //are we trying to get or set
     switch ($action) {
         // sets a value for a field to null
         case 'del_':
             // we can not delete this special value
             if ($requested_field == 'added') {
                 throw new ModelException('you can not delete the added value, it is managed by the database for you');
             } else {
                 // set the value to null
                 $this->values[$variable_name] = null;
             }
             break;
         case 'get_':
             // if we called a get method without ID (i.e. getUser instead of getUserID) then we build the model and return it
             if ($passing_model) {
                 // do we have an ID for this type of object to be built
                 if ($this->values[$variable_name]) {
                     return m($requested_field, $this->values[$variable_name]);
                 } else {
                     return null;
                 }
             } else {
                 return array_key_exists($variable_name, $this->values) ? $this->values[$variable_name] : null;
             }
             break;
         case 'set_':
             if ($requested_field == 'added') {
                 throw new ModelException('you can not set the added value, it is created by the database for you');
             }
             // ensure this is an array and is not empty
             if (is_array($arguments) && $arguments) {
                 // take the first argument
                 $var = reset($arguments);
                 // if we called a set method for an ID field but are passing a model then we take the ID from the model
                 if ($passing_model) {
                     // check the model we are passing in is valid
                     if ($var instanceof Model) {
                         // get the id from the model, and save that
                         if ($id = $var->getID()) {
                             $this->values[$variable_name] = $id;
                         } else {
                             throw new ModelException('calling method ' . $name . ' with a model which doesnt have an id');
                         }
                     } else {
                         throw new ModelException('calling method ' . $name . ' was expecting a model as the first parameter but got a ' . get_class($model));
                     }
                 } else {
                     $this->values[$variable_name] = $var;
                 }
             } else {
                 throw new ModelException('calling method ' . $name . ' on a model requires a parameter');
             }
             break;
         default:
             // no function
             trigger_error('Call to undefined method ' . get_class($this) . '::' . $name . '()', E_USER_ERROR);
             break;
     }
 }
예제 #24
0
 /**
  * select items with a select statment
  * 
  * @depends testAddMultipleRecords
  */
 function testSelectQuery()
 {
     // sleep for atleast one second between methods, it is only 'eventual consistency'
     sleep(1);
     $query = "select * from {$this->test_domain} where `letter_position` between '07' and '12' ";
     $result = SimpleDB::select($query);
     // assert 6 results came back
     $this->assertArrayCount($result, 6);
     // assert this known result was as expected, if so, assumme the rest are correct also
     $this->assertTrue(array_val($result, array('j', 'letter_position')) == '09');
 }
예제 #25
0
파일: error.php 프로젝트: Tapac/hotscot
 function error500($params)
 {
     $tpl_vars = array('message' => array_val($params, 'message'), 'code' => 500);
     v('error/500', $tpl_vars);
 }
예제 #26
0
파일: simple_db.php 프로젝트: Tapac/hotscot
 /**
  * call the remote simpledb service
  *
  * @return void
  * @author Craig Ulliott
  */
 private static function exec(array $params)
 {
     $start_time = microtime(true);
     // by default, we try operations thrice before acknowledging failure
     $attempt = 0;
     // ue a loop to keep trying
     while (1) {
         ++$attempt;
         // catch errors so we can try again
         try {
             // get the curl handle setup with the required params
             $ch = self::get_curl_handle($params);
             // excecute the curl handle
             $response = curl_exec($ch);
             // close the handler
             curl_close($ch);
             // parse the result
             $result = self::format_result($response);
             $duration = microtime(true) - $start_time;
             //log the query
             Log::addQuery('simpledb', array_val($params, 'Action'), $duration);
             return $result;
         } catch (SimpleDbException $e) {
             // if we have run out of tries, throw the exception further up
             if ($attempt >= 3) {
                 throw $e;
             }
         }
     }
 }