Exemple #1
0
function pie_response_content()
{
    $serve_fbml = Pie_Request::accepts('text/fbml');
    if ($serve_fbml) {
        // add more fbjs files here
    } else {
        // the js files for your app
        Pie_Response::addScript('plugins/pie/js/Pie.js');
        Pie_Response::addScript("http://cdn.jquerytools.org/1.2.3/jquery.tools.min.js");
        Pie_Response::addScript('plugins/users/js/Users.js');
        // See views/layout/html.php for a facebook script at the top of the <body>
    }
    Pie_Response::addStylesheet('plugins/pie/css/Ui.css');
    $app = Pie_Config::expect('pie', 'app');
    $url = Pie_Request::url();
    $module = Pie_Dispatcher::uri()->module;
    if (empty($module)) {
        return Pie::event("{$app}/notFound/response/content");
    }
    $action = Pie_Dispatcher::uri()->action;
    $event = "{$module}/{$action}/response/content";
    if (!Pie::canHandle($event)) {
        return Pie::event("{$app}/notFound/response/content");
    }
    // Go ahead and fire the event, returning the result.
    return Pie::event($event);
}
Exemple #2
0
function users_activate_validate()
{
    $email_address = Pie_Dispatcher::uri()->email_address;
    $mobile_number = Pie_Dispatcher::uri()->mobile_number;
    if ($email_address && !Pie_Valid::email($email_address)) {
        throw new Pie_Exception_WrongValue(array('field' => 'email', 'range' => 'a valid email address'), 'email_address');
    }
    if ($mobile_number && !Pie_Valid::phone($mobile_number)) {
        throw new Pie_Exception_WrongValue(array('field' => 'mobile phone', 'range' => 'a valid phone number'), 'mobile_number');
    }
    if ($email_address or $mobile_number) {
        if (empty($_REQUEST['code'])) {
            throw new Pie_Exception("The activation code is missing");
        }
    }
    // This is one of the few places where we cheat,
    // and fill the $_POST array even though it probably wasn't filled.
    if ($email_address) {
        $_POST['email_address'] = $email_address;
    } else {
        if ($mobile_number) {
            $_POST['mobile_number'] = $mobile_number;
        }
    }
}
Exemple #3
0
 static function execute()
 {
     // Fixes for different platforms:
     if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
         // ISAPI 3.0
         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
     }
     // Define a constant
     if (!defined('PIE_CONTROLLER')) {
         define('PIE_CONTROLLER', 'Pie_WebController');
     }
     try {
         Pie::log("Request for " . Pie_Request::url(true));
         Pie_Dispatcher::dispatch();
         $dispatch_result = Pie_Dispatcher::result();
         if (!isset($dispatch_result)) {
             $dispatch_result = 'Ran dispatcher';
         }
         $uri = Pie_Dispatcher::uri();
         $module = $uri->module;
         $action = $uri->action;
         if ($module and $action) {
             $slot_names = Pie_Request::slotNames();
             $requested_slots = empty($slot_names) ? '' : implode(',', array_keys($slot_names));
             Pie::log("~" . ceil(Pie::microtime()) . 'ms+' . ceil(memory_get_peak_usage() / 1000) . 'kb.' . " {$dispatch_result} for {$module}/{$action}" . " ({$requested_slots})");
         } else {
             Pie::log("~" . ceil(Pie::microtime()) . 'ms+' . ceil(memory_get_peak_usage() / 1000) . 'kb.' . " No route for " . $_SERVER['REQUEST_URI']);
         }
     } catch (Exception $exception) {
         Pie::event('pie/exception', compact('exception'));
     }
 }
Exemple #4
0
/**
 * Default pie/notFound handler.
 * Just displays pie/notFound.php view.
 */
function pie_notFound($params)
{
    header("HTTP/1.0 404 Not Found");
    Pie_Dispatcher::result("Nothing found");
    $url = Pie_Request::url();
    echo Pie::view('pie/notFound.php', compact('url'));
}
Exemple #5
0
/**
 * Override pie/noModule handler.
 * just goes on to render our app's response,
 * which will echo a 404 view.
 */
function pie_noModule($params)
{
    if (!Pie_Request::accepts('text/fbml')) {
        header("HTTP/1.0 404 Not Found");
    }
    Pie_Dispatcher::uri()->module = Pie_Config::expect('pie', 'app');
    Pie_Dispatcher::uri()->action = '';
    Pie::event('pie/response', $params);
}
Exemple #6
0
/**
 * Override pie/notFound handler.
 * just goes on to render our app's response,
 * which will echo a 404 view.
 */
function pie_notFound($params)
{
    if (!Pie_Dispatcher::uri()->facebook) {
        header("HTTP/1.0 404 Not Found");
    }
    Pie_Dispatcher::uri()->module = Pie_Config::expect('pie', 'app');
    Pie_Dispatcher::uri()->action = 'notFound';
    Pie::event('pie/response', $params);
}
Exemple #7
0
function users_after_pie_reroute($params, &$stop_dispatch)
{
    $uri = Pie_Dispatcher::uri();
    $app = Pie_Config::expect('pie', 'app');
    $ma = $uri->module . '/' . $uri->action;
    $requireComplete = Pie_Config::get('users', 'requireComplete', array());
    if (isset($requireComplete[$ma])) {
        $redirect_action = is_string($requireComplete[$ma]) ? $requireComplete[$ma] : "{$app}/login";
        $test_complete = true;
    } else {
        $requireLogin = Pie_Config::get('users', 'requireLogin', array());
        if (!isset($requireLogin[$ma])) {
            // We don't have to require complete or login here
            return;
        }
        $redirect_action = is_string($requireLogin[$ma]) ? $requireLogin[$ma] : "{$app}/login";
    }
    // First, try to get the user
    $user = Users::loggedInUser();
    if (!$user) {
        // Try authenticating with facebook
        $module = Pie_Dispatcher::uri()->module;
        $app_id = Pie_Config::expect('users', 'facebookApps', $module, 'appId');
        $user = Users::authenticate('facebook', $app_id);
    }
    if (!$user) {
        $uri->onSuccess = $uri->module . '/' . $uri->action;
        $uri->onCancel = "{$app}/welcome";
        if ($uri->onSuccess === $redirect_action) {
            // avoid a redirect loop
            $uri->onSuccess = "{$app}/home";
        }
        $parts = explode('/', $redirect_action);
        $uri->action = $parts[0];
        $uri->action = $parts[1];
    }
    // If have requireLogin but not requireComplete, then
    // simply change the underlying URI without redirecting
    if (empty($test_complete)) {
        return;
    }
    // If we are here, we should check if the user account is complete
    $complete = Pie::event('users/account/complete');
    if ($complete) {
        // good, nothing else to complete
        return;
    }
    // redirect to account page
    $account_action = Pie_Config::expect('users', 'accountAction', $uri->module);
    if ($ma != $account_action) {
        // Make the user launch into setting up their account.
        // If they want to return to this URL later, they can do it on their own.
        Pie_Response::redirect($account_action);
        $stop_dispatch = true;
        return;
    }
}
Exemple #8
0
function pie_response_title()
{
    // The default title
    $title = Pie_Config::get('pie', 'app', basename(APP_DIR));
    $action = Pie_Dispatcher::uri()->action;
    if ($action) {
        $title .= ": {$action}";
    }
    return $title;
}
Exemple #9
0
function pie_post($params)
{
    $uri = Pie_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (!Pie::canHandle("{$module}/{$action}/post")) {
        return null;
    }
    return Pie::event("{$module}/{$action}/post", $params);
}
Exemple #10
0
 static function execute()
 {
     // Fixes for different platforms:
     if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
         // ISAPI 3.0
         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
     }
     // Define a constant
     if (!defined('PIE_CONTROLLER')) {
         define('PIE_CONTROLLER', 'Pie_ActionController');
     }
     try {
         $parts = explode('/', Pie_Request::tail());
         $parts_len = count($parts);
         if ($parts_len >= 1) {
             $module = $parts[0];
         }
         if ($parts_len >= 2) {
             $action = $parts[1];
         }
         // Make sure the 'pie'/'web' config fields are set,
         // otherwise URLs will be formed pointing to the wrong
         // controller script.
         $ar = Pie_Config::get('pie', 'web', 'appRootUrl', null);
         if (!isset($ar)) {
             throw new Pie_Exception_MissingConfig(array('fieldpath' => 'pie/web/appRootUrl'));
         }
         $cs = Pie_Config::get('pie', 'web', 'controllerSuffix', null);
         if (!isset($cs)) {
             throw new Pie_Exception_MissingConfig(array('fieldpath' => 'pie/web/controllerSuffix'));
         }
         // Dispatch the request
         $uri = Pie_Uri::from(compact('module', 'action'));
         Pie_Dispatcher::dispatch($uri);
         $dispatch_result = Pie_Dispatcher::result();
         if (!isset($dispatch_result)) {
             $dispatch_result = 'Ran dispatcher';
         }
         $uri = Pie_Dispatcher::uri();
         $module = $uri->module;
         $action = $uri->action;
         if ($module and $action) {
             $slot_names = Pie_Request::slotNames();
             $requested_slots = empty($slot_names) ? '' : implode(',', array_keys($slot_names));
             Pie::log("~" . ceil(Pie::microtime()) . 'ms+' . ceil(memory_get_peak_usage() / 1000) . 'kb.' . " {$dispatch_result} for {$module}/{$action}" . " ({$requested_slots})");
         } else {
             Pie::log("~" . ceil(Pie::microtime()) . 'ms+' . ceil(memory_get_peak_usage() / 1000) . 'kb.' . " No route for " . $_SERVER['REQUEST_URI']);
         }
     } catch (Exception $exception) {
         Pie::event('pie/exception', compact('exception'));
     }
 }
Exemple #11
0
function users_activate_post()
{
    $email_address = Pie_Dispatcher::uri()->email_address;
    $mobile_number = Pie_Dispatcher::uri()->mobile_number;
    $email = null;
    $mobile = null;
    if ($email_address) {
        $email = new Users_Email();
        $email->address = $email_address;
        // NOTE: not sharded by user_id
        if (!$email->retrieve()) {
            throw new Pie_Exception_MissingRow(array('table' => 'email', 'criteria' => "address = {$email_address}"));
        }
        $user = new Users_User();
        $user->id = $email->user_id;
        if (!$user->retrieve()) {
            throw new Pie_Exception_MissingRow(array('table' => 'user', 'criteria' => 'id = ' . $user->id));
        }
        if ($email->activation_code != $_REQUEST['code']) {
            throw new Pie_Exception("The activation code does not match.", 'code');
        }
        $user->setEmailAddress($email->address);
        // may throw exception
        $type = "email address";
    }
    if ($mobile_number) {
        $mobile = new Users_Mobile();
        $mobile->number = $mobile_number;
        // NOTE: not sharded by user_id
        if (!$mobile->retrieve()) {
            throw new Pie_Exception_MissingRow(array('table' => 'mobile phone', 'criteria' => "number = {$mobile_number}"));
        }
        $user = new Users_User();
        $user->id = $mobile->user_id;
        if (!$user->retrieve()) {
            throw new Pie_Exception_MissingRow(array('table' => 'user', 'criteria' => 'id = ' . $user->id));
        }
        if ($mobile->activation_code != $_REQUEST['code']) {
            throw new Pie_Exception("The activation code does not match.", 'code');
        }
        $user->setMobileNumber($mobile->number);
        // may throw exception
        $type = "mobile number";
    }
    if ($type) {
        Pie_Response::addNotice("users/activate", "Your {$type} has been activated.");
    }
    Users::$cache['user'] = $user;
}
Exemple #12
0
/**
 * The default implementation.
 */
function pie_errors($params)
{
    extract($params);
    /**
     * @var Exception $exception
     */
    if (!empty($exception)) {
        Pie_Response::addError($exception);
        $errors = Pie_Response::getErrors();
    }
    $errors_array = Pie_Exception::toArray($errors);
    $exception_array = Pie_Exception::toArray($exception);
    // Simply return the errors, if this was an AJAX request
    if ($is_ajax = Pie_Request::isAjax()) {
        switch (strtolower($is_ajax)) {
            case 'json':
            default:
                $json = json_encode(array('errors' => $errors_array, 'exception' => $exception_array));
                $callback = Pie_Request::callback();
                echo $callback ? "{$callback}({$json})" : $json;
        }
        return;
    }
    // Forward internally, if it was requested
    if (isset($_REQUEST['_pie']['onErrors'])) {
        $uri = Pie_Dispatcher::uri();
        $uri2 = Pie_Uri::from($_REQUEST['_pie']['onErrors']);
        if ($uri !== $uri2) {
            Pie_Dispatcher::forward($uri2);
            return;
            // we don't really need this, but it's here anyway
        }
    }
    if (Pie::eventStack('pie/response')) {
        // Errors happened while rendering response. Just render errors view.
        return Pie::view('pie/errors.php', $params);
    }
    try {
        // Try rendering the response, expecting it to
        // display the errors along with the rest.
        $ob = new Pie_OutputBuffer();
        Pie::event('pie/response', compact('errors', 'exception', 'errors_array', 'exception_array'));
        $ob->endFlush();
    } catch (Exception $exception) {
        $output = $ob->getClean();
        return Pie::event('pie/exception', compact('exception'));
    }
}
Exemple #13
0
function users_activate_response_content()
{
    $uri = Pie_Dispatcher::uri();
    $email_address = $uri->email_address;
    $mobile_number = $uri->mobile_number;
    if ($uri->email_address) {
        $type = 'email address';
    } else {
        if ($uri->mobile_number) {
            $type = 'mobile_number';
        } else {
            $type = '';
        }
    }
    $user = Pie::ifset(Users::$cache['user'], false);
    return Pie::view('users/content/activate.php', compact('email_address', 'mobile_number', 'type', 'user'));
}
Exemple #14
0
function pie_response_default($params)
{
    if (!isset($params['slot_name'])) {
        throw new Pie_Exception_RequiredField(array('field' => '$slot_name'));
    }
    $slot_name = $params['slot_name'];
    $uri = Pie_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (Pie::canHandle("{$module}/{$action}")) {
        Pie::event("{$module}/{$action}");
    }
    $event = "{$module}/{$action}/response/{$slot_name}";
    if (Pie::canHandle($event)) {
        return Pie::event($event);
    }
    return "Need to define {$event}";
}
Exemple #15
0
function pie_addScriptLines()
{
    $app = Pie_Config::expect('pie', 'app');
    $uri = Pie_Dispatcher::uri();
    $proxies_json = json_encode(Pie_Config::get('pie', 'proxies', array()));
    $uri_json = json_encode($uri->toArray());
    $url = Pie_Request::url();
    $url_json = json_encode($url);
    $proxy_url_json = json_encode(Pie_Uri::url($url));
    $base_url = json_encode(Pie_Request::baseUrl());
    Pie_Response::addScriptLine(<<<EOT
// pie {{
\t\tPie.info = {
\t\t\t"proxies": {$proxies_json},
\t\t\t"uri": {$uri_json},
\t\t\t"url": {$url_json},
\t\t\t"proxyUrl": {$proxy_url_json},
\t\t\t"baseUrl": {$base_url}
\t\t};
EOT
);
    $uris = Pie_Config::get('pie', 'javascript', 'uris', array());
    $urls = array();
    foreach ($uris as $u) {
        $urls["{$u}"] = Pie_Uri::url("{$u}");
    }
    $urls_json = json_encode($urls);
    Pie_Response::addScriptLine("\t\tPie.urls = {$urls_json};");
    // Export more variables to inline js
    $app = Pie_Config::expect('pie', 'app');
    $app_json = json_encode($app);
    Pie_Response::addScriptLine("\t\tPie.app = {$app_json};\n" . "// }} pie");
    $snf = Pie_Config::get('pie', 'session', 'nonceField', 'nonce');
    $nonce = isset($_SESSION[$snf]) ? $_SESSION[$snf] : null;
    if ($nonce) {
        $nonce_json = json_encode($nonce);
        Pie_Response::addScriptLine("\t\tPie.nonce = {$nonce_json};");
    }
}
Exemple #16
0
 protected static function errors($exception, $module, $partial_response = null)
 {
     // In the handlers below, you can get errors with:
     // $errors = Pie_Response::getErrors();
     try {
         if (self::$handling_errors) {
             // We need to handle errors, but we
             // have already tried to do it.
             // Just show the errors view.
             echo Pie::view('pie/errors.php', compact('errors'));
             return;
         }
         self::$handling_errors = true;
         if (Pie::canHandle("{$module}/errors")) {
             Pie::event("{$module}/errors", compact('errors', 'exception', 'partial_response'));
         } else {
             Pie::event("pie/errors", compact('errors', 'exception', 'partial_response'));
         }
     } catch (Exception $e) {
         Pie::event('pie/exception', array('exception' => $e));
     }
 }
Exemple #17
0
 /**
  * Renders pie-specific information for a form
  * @param string $on_success
  *  The URI or URL to redirect to in case of success
  *  If you put "true" here, it uses $_REQUEST['_pie']['onSuccess'],
  *  or if it's not there, then Pie_Dispatcher::uri()
  * @param string $on_errors
  *  Optional. The URI or URL to redirect to in case of errors
  *  If you put "true" here, it uses $_REQUEST['_pie']['onSuccess'],
  *  or if it's not there, then Pie_Dispatcher::uri()
  * @param string $session_nonce_field
  *  Optional. The name of the nonce field to use in the session.
  *  If the config parameter "pie"/"session"/"nonceField" is set, uses that.
  * @return string
  *  The generated markup
  */
 static function formInfo($on_success, $on_errors = null, $session_nonce_field = null)
 {
     $uri = Pie_Dispatcher::uri();
     if ($on_success === true) {
         $on_success = Pie::ifset($_REQUEST['_pie']['onSuccess'], $uri);
     }
     if ($on_errors === true) {
         $on_errors = Pie::ifset($_REQUEST['_pie']['onSuccess'], $uri);
     }
     $hidden_fields = array();
     if (isset($on_success)) {
         $hidden_fields['_pie[onSuccess]'] = Pie_Uri::url($on_success);
     }
     if (isset($on_errors)) {
         $hidden_fields['_pie[onErrors]'] = Pie_Uri::url($on_errors);
     }
     if (!isset($session_nonce_field)) {
         $session_nonce_field = Pie_Config::get('pie', 'session', 'nonceField', 'nonce');
     }
     if (isset($session_nonce_field)) {
         if (!isset($_SESSION['pie'][$session_nonce_field])) {
             $_SESSION['pie'][$session_nonce_field] = uniqid();
         }
         $hidden_fields['_pie[nonce]'] = $_SESSION['pie'][$session_nonce_field];
     }
     return self::hidden($hidden_fields);
 }
Exemple #18
0
/**
 * Default pie/response handler.
 * 1. Gets some slots, depending on what was requested.
 * 2. Renders them in a layout
 *    The layout expects "title", "dashboard" and "contents" slots to be filled.
 */
function pie_response($params)
{
    extract($params);
    /**
     * @var Exception $exception
     * @var array $errors
     */
    // Redirect to success page, if requested.
    $is_ajax = Pie_Request::isAjax();
    if (empty($errors) and empty($exception)) {
        if (!$is_ajax and isset($_REQUEST['_pie']['onSuccess'])) {
            $on_success = $_REQUEST['_pie']['onSuccess'];
            if (Pie_Config::get('pie', 'response', 'onSuccessShowFrom', true)) {
                $on_success = Pie_Uri::url($on_success . '?_pie[fromSuccess]=' . Pie_Dispatcher::uri());
            }
            Pie_Response::redirect($on_success);
            return;
        }
    }
    // Get the requested module
    $uri = Pie_Dispatcher::uri();
    if (!isset($module)) {
        $module = $uri->module;
        if (!isset($module)) {
            $module = 'pie';
            Pie_Dispatcher::uri()->module = 'pie';
        }
    }
    // Get the main module (the app)
    $app = Pie_Config::expect('pie', 'app');
    // Add some javascript to inform the front end of important URLs
    Pie::event('pie/addScriptLines');
    // What to do if this is an AJAX request
    if ($is_ajax) {
        $slot_names = Pie_Request::slotNames();
        if (!isset($slot_names)) {
            $slot_names = Pie_Config::get($module, 'response', 'slotNames', array('content' => null, 'dashboard' => null, 'title' => null, 'notices' => null));
        }
        $slots = array();
        $stylesheets = array();
        $stylesInline = array();
        $scripts = array();
        $scriptLines = array();
        if (is_array($slot_names)) {
            foreach ($slot_names as $slot_name => $v) {
                $slots[$slot_name] = Pie_Response::fillSlot($slot_name, 'default');
                $stylesheets[$slot_name] = Pie_Response::stylesheetsArray($slot_name);
                $stylesInline[$slot_name] = Pie_Response::stylesInline($slot_name);
                $scripts[$slot_name] = Pie_Response::scriptsArray($slot_name);
                $scriptLines[$slot_name] = Pie_Response::scriptLines($slot_name);
            }
        }
        $timestamp = microtime(true);
        $echo = Pie_Request::contentToEcho();
        // Render a JSON layout for ajax
        $to_encode = compact('slots', 'stylesheets', 'stylesInline', 'scripts', 'scriptLines', 'timestamp', 'echo');
        // Cut down on the response size
        foreach (array('slots', 'stylesheets', 'stylesInline', 'scripts', 'scriptLines') as $f) {
            $is_empty = true;
            if (is_array($to_encode[$f])) {
                foreach ($to_encode[$f] as $k => $v) {
                    if (isset($v)) {
                        $is_empty = false;
                    } else {
                        unset($to_encode[$f][$k]);
                    }
                }
            } else {
                if (!empty($to_encode[$f])) {
                    $is_empty = false;
                }
            }
            if ($is_empty) {
                unset($to_encode[$f]);
            }
        }
        switch (strtolower($is_ajax)) {
            case 'json':
            default:
                $json = json_encode($to_encode);
                $callback = Pie_Request::callback();
                echo $callback ? "{$callback}({$json})" : $json;
        }
        return;
    }
    // If this is a request for a regular webpage,
    // fill the usual slots and render a layout.
    // Attach stylesheets and scripts
    if (Pie_Request::accepts('text/fbml')) {
        Pie_Response::addStylesheet("css/fbml.css");
        Pie_Response::addScript('plugins/pie/fbjs/Pie.fb.js');
    } else {
        Pie_Response::addStylesheet("css/html.css");
        Pie_Response::addScript('plugins/pie/js/Pie.js');
    }
    // Get all the usual slots for a webpage
    $slot_names = Pie_Config::get($module, 'response', 'slotNames', array('content' => null, 'dashboard' => null, 'title' => null, 'notices' => null));
    $slots = array();
    foreach ($slot_names as $sn => $v) {
        $slots[$sn] = Pie_Response::fillSlot($sn, 'default');
    }
    $output = Pie_Response::output();
    if (isset($output)) {
        if ($output === true) {
            return;
        }
        if (is_string($output)) {
            echo $output;
        }
        return;
    }
    if (Pie_Request::accepts('text/fbml')) {
        // Render a full FBML layout
        $layout_view = Pie_Config::get($app, 'response', 'layout_fbml', "{$app}/layout/fbml.php");
        echo Pie::view($layout_view, $slots);
    } else {
        // Render a full HTML layout
        $layout_view = Pie_Config::get($app, 'response', 'layout_html', "{$app}/layout/html.php");
        echo Pie::view($layout_view, $slots);
    }
}
Exemple #19
0
 /**
  * Get the status of the logged-in user and their account.
  * @param Users_Email $email
  *  Optional. Pass a reference here to be filled with the email object, if it's loaded.
  *  You can use it in conjunction with the "verify email" status.
  * @return array|boolean
  *  Returns false if the user is not logged in.
  *  Returns true if everything is complete.
  *  Otherwise, returns an array whose keys are the names of the missing fields:
  *  ("first_name", "last_name", "birthday", "gender", "desired_gender", "username",
  *  "email_address")
  *  and the values are "missing" or "unverified"
  */
 static function accountStatus(&$email = null)
 {
     $module = Pie_Dispatcher::uri()->module;
     $user = Users::loggedInUser();
     if (!$user) {
         // Try to authenticate
         $app_id = Pie_Config::expect('users', 'facebookApps', $module, 'appId');
         $user = Users::authenticate('facebook', $app_id);
         if (!$user) {
             return false;
         }
     }
     $result = array();
     if (empty($user->email_address)) {
         // An email address isn't verified for this user yet.
         // If the user hasn't even added an email address, then ask for one.
         if (!isset(self::$email)) {
             self::$email = new Users_Email();
             self::$email->user_id = $user->id;
             self::$email = self::$email->retrieve(null, false, '*', true)->orderBy('time_created', false)->resume();
         }
         $email = self::$email;
         if ($email) {
             // The email could be unverified, sunspended, unsubscribed, etc.
             $result['email_address'] = $email->state;
         } else {
             $result['email_address'] = 'missing';
         }
     }
     $fieldnames = array('first_name', 'last_name', 'username', 'birthday', 'gender', 'desired_gender', 'relationship_status', 'relationship_user_id', 'zipcode');
     foreach ($fieldnames as $k => $v) {
         if (empty($user->{$v})) {
             $result[$v] = 'missing';
         }
     }
     return $result;
 }
Exemple #20
0
function items_addPhoto_post()
{
    if (Pie_Dispatcher::uri()->facebook) {
        return;
    }
    if (isset($_POST['fb_sig_app_id'])) {
        $app_id = $_POST['fb_sig_app_id'];
    } else {
        $app = Pie_Config::expect('pie', 'app');
        $app_id = Pie_Config::expect('users', 'facebookApps', $app, 'appId');
    }
    Users::authenticate('facebook', $app_id);
    /*
    if (!isset($_REQUEST['content'])) {
    	Pie_Response::addError(new Pie_Exception_RequiredField(array(
    		'field' => 'content'
    	)));
    	Pie_Dispatcher::showErrors();
    	return;
    }
    */
    $user = Users::loggedInUser();
    if (!$user) {
        throw new Users_Exception_NotLoggedIn();
    }
    // TODO: download a backup copy into a special place for facebook photos
    // TODO: handle uploads
    // Facebook photo
    if (!empty($_POST['src_big'])) {
        if (!is_array($_POST['src_big'])) {
            throw new Exception("src_big must be an array");
        }
        // First, we download the photo to store on our site
        foreach ($_POST['src_big'] as $pid => $src_big) {
            $src_small = Pie::ifset($_POST['src_small'][$pid], $src_big);
            $parts = explode('/', $src_big);
            $parts = explode('.', end($parts));
            $ext = end($parts);
            $filename = 'photos' . DS . 'facebook' . DS . "pid{$pid}.{$ext}";
            $abs_filename = ITEMS_PLUGIN_FILES_DIR . DS . $filename;
            if (file_exists($abs_filename)) {
                // A photo was already copied to this filename
                Pie_Config::set('items', 'addPhoto', 'result', 'exists');
                $photo = new Items_Photo();
                $photo->filename = $filename;
                if ($photo = $photo->retrieve()) {
                    $item = new Items_Item();
                    $item->id = $photo->item_id;
                    $item = $item->retrieve();
                    // relies on DB consistency
                    Pie_Config::set('items', 'addPhoto', 'item_id', $item->id);
                    Pie_Config::set('items', 'addPhoto', 'state', $item->state);
                }
                return;
            }
            copy($src_big, $abs_filename);
            $item = new Items_Item();
            $item->by_user_id = $user->id;
            $item->thumb_url = $src_small;
            $item->share_count = 0;
            $item->state = 'pending';
            Pie::event('items/addPhoto/saveItem', compact('item'), 'before');
            $item->save();
            $photo = new Items_Photo();
            $photo->src_url = $src_big;
            $photo->filename = $filename;
            $photo->item_id = $item->id;
            Pie::event('items/addPhoto/savePhoto', compact('photo'), 'before');
            $photo->save();
        }
    } else {
        if (isset($_FILES['upload'])) {
            // TODO: maybe add checks for size, mime type, etc.
            if ($errcode = $_FILES['upload']['error']) {
                $code = $_FILES['upload']['error'];
                throw new Pie_Exception_UploadError(compact('code'));
            }
            $parts = explode('.', $_FILES['upload']['name']);
            $ext = end($parts);
            $uniqid = isset($_POST['uniqid']) ? $_POST['uniqid'] : uniqid('up.', false);
            $md5 = md5($_FILES['upload']['name']);
            $dirname = 'photos' . DS . 'user' . $user->id;
            $abs_dirname = ITEMS_PLUGIN_FILES_DIR . DS . $dirname;
            if (!file_exists($abs_dirname)) {
                mkdir($abs_dirname, 0777, true);
            }
            $filename = $dirname . DS . "{$uniqid}.{$md5}.{$ext}";
            $abs_filename = ITEMS_PLUGIN_FILES_DIR . DS . $filename;
            if (file_exists($abs_filename)) {
                // A file was already uploaded via this uniqid
                Pie_Config::set('items', 'addPhoto', 'result', 'exists');
                $photo = new Items_Photo();
                $photo->filename = $filename;
                if ($photo = $photo->retrieve()) {
                    $item = new Items_Item();
                    $item->id = $photo->item_id;
                    $item = $item->retrieve();
                    // relies on DB consistency
                    Pie_Config::set('items', 'addPhoto', 'item_id', $item->id);
                    Pie_Config::set('items', 'addPhoto', 'state', $item->state);
                }
                return;
            }
            move_uploaded_file($_FILES['upload']['tmp_name'], $abs_filename);
            $src_big = 'plugins/items/photos/user' . $user->id . "/{$uniqid}.{$md5}.{$ext}";
            $src_small = $src_big;
            // TODO: make small version!!!! AND PUT INTO thumb_url
            // Try different functions if they exist, from graphics libs
            $item = new Items_Item();
            $item->by_user_id = $user->id;
            $item->thumb_url = $src_small;
            $item->share_count = 0;
            $item->state = 'pending';
            Pie::event('items/addPhoto/saveItem', compact('item'), 'before');
            $item->save();
            $photo = new Items_Photo();
            $photo->src_url = $src_big;
            $photo->filename = $filename;
            $photo->item_id = $item->id;
            Pie::event('items/addPhoto/savePhoto', compact('photo'), 'before');
            $photo->save();
        }
    }
    // Report as added
    if (!empty($item)) {
        Pie_Config::set('items', 'addPhoto', 'result', 'added');
        Pie_Config::set('items', 'addPhoto', 'item_id', $item->id);
        Pie_Config::set('items', 'addPhoto', 'state', $item->state);
    }
}