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; } } }
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')); } }
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); }
/** * 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); }
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; } }
/** * 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); }
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; }
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); }
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')); } }
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; }
/** * 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')); } }
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')); }
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}"; }
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};"); } }
/** * 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); }
/** * 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); } }
/** * 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; }
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); } }
/** * Dispatches a URI for internal processing. * Usually called by a front controller. * @param mixed $uri * Optional. You can pass a custom URI to dispatch. Otherwise, PIE will attempt * to route the requested URL, if any. * @param array $check * Optional. Pass array() to skip checking whether the URI can be obtained * as a result of routing some URL. * @return boolean */ static function dispatch($uri = null, $check = array('accessible')) { if (!is_array($check)) { $check = array('accessible'); } if (isset($uri)) { if (in_array('accessible', $check)) { if (!Pie_Uri::url($uri)) { // We shouldn't dispatch to this URI $uri = Pie_Uri::from(array()); } } self::$uri = Pie_Uri::from($uri); } else { self::$uri = Pie_Request::uri(); } // if file or dir is requested, try to serve it $served = false; $skip = Pie_Config::get('pie', 'dispatcherSkipFilename', false); $filename = $skip ? false : Pie_Request::filename(); if ($filename) { if (is_dir($filename)) { $served = Pie::event("pie/dir", compact('filename', 'routed_uri')); $dir_was_served = true; } else { $served = Pie::event("pie/file", compact('filename', 'routed_uri')); $dir_was_served = false; } } // if response was served, then return if ($served) { self::result($dir_was_served ? "Dir served" : "File served"); return true; } // This loop is for forwarding $max_forwards = Pie_Config::get('pie', 'maxForwards', 10); for ($try = 0; $try < $max_forwards; ++$try) { // Make an array from the routed URI $routed_uri_array = array(); if (self::$uri instanceof Pie_Uri) { $routed_uri_array = self::$uri->toArray(); } // If no module was found, then respond with noModule and return if (!isset(self::$uri->module)) { Pie::event("pie/noModule", $routed_uri_array); // should echo things self::result("No module"); return false; } $module = self::$uri->module; // Implement restricting of modules we are allowed to access $routed_modules = Pie_Config::get('pie', 'routedModules', null); if (isset($routed_modules)) { if (!in_array($module, $routed_modules)) { Pie::event('pie/notFound', $routed_uri_array); // should echo things self::result("Unknown module"); return false; } } else { if (!Pie::realPath("handlers/{$module}")) { Pie::event('pie/notFound', $routed_uri_array); // should echo things self::result("Unknown module"); return false; } } try { // Fire a pure event, for aggregation etc if (!in_array('pie/prepare', self::$skip)) { Pie::event('pie/prepare', $routed_uri_array, true); } // Perform validation if (!in_array('pie/validate', self::$skip)) { Pie::event('pie/validate', $routed_uri_array); // Check if any errors accumulated if (Pie_Response::getErrors()) { // There were validation errors -- render a response self::errors(null, $module, null); self::result('Validation errors'); return false; } } // Time to instantiate some app objects from the request if (!in_array('pie/objects', self::$skip)) { Pie::event('pie/objects', $routed_uri_array, true); } // We might want to reroute the request if (!in_array('pie/reroute', self::$skip)) { $stop_dispatch = Pie::event('pie/reroute', $routed_uri_array, true); if ($stop_dispatch) { self::result("Stopped dispatch"); return false; } } if (Pie_Request::isPost()) { if (!in_array('pie/post', self::$skip)) { // Make some changes to server state, possibly Pie::event('pie/post', $routed_uri_array); } } // Time to instantiate some app objects from the request if (!in_array('pie/analytics', self::$skip)) { Pie::event('pie/analytics', $routed_uri_array, true); } // Start buffering the response, unless otherwise requested if ($handler = Pie_Response::isBuffered()) { $ob = new Pie_OutputBuffer($handler); } // Generate and render a response Pie::event("pie/response", $routed_uri_array); if (!empty($ob)) { $ob->endFlush(); } self::result("Served response"); return true; } catch (Pie_Exception_DispatcherForward $e) { // Go again, this time with a different URI. self::$uri = Pie_Uri::from($e->uri); if (is_array($e->skip)) { self::$skip = $e->skip; } else { // Don't process the POST fields this time around self::$skip = array('pie/post'); } // We'll be handling errors anew self::$handling_errors = false; } catch (Pie_Exception_DispatcherErrors $e) { if (!empty($ob)) { $partial_response = $ob->getClean(); } else { $partial_response = null; } self::errors(null, $module, $partial_response); self::result("Rendered errors"); return true; } catch (Exception $exception) { if (!empty($ob)) { $partial_response = $ob->getClean(); } else { $partial_response = null; } self::errors($exception, $module, $partial_response); self::result("Exception occurred"); return false; } } // If we are here, we have done forwarding too much throw new Pie_Exception_Recursion(array('function_name' => 'Dispatcher::forward()')); }