public static function handleRequest()
 {
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     return static::handleSearchRequest();
 }
 public static function handleRequest()
 {
     $GLOBALS['Session']->requireAccountLevel('Developer');
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     switch ($handle = static::shiftPath()) {
         case '':
         case false:
         case 'classes':
             return static::handleClassesRequest();
         case 'sql':
             return static::handleSQLRequest();
         case 'ext-model':
             return static::handleExtModelRequest();
         case 'ext-columns':
             return static::handleExtColumnsRequest();
         case 'index':
             return static::handleManagerRequest();
         case 'renest':
             return static::handleRenestRequest();
         default:
             return static::throwNotFoundError();
     }
 }
 public static function handleRequest()
 {
     // handle json response mode
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     // get token
     if (!($tokenHandle = static::shiftPath())) {
         return static::throwInvalidRequestError();
     }
     if (!($Token = Token::getByHandle($tokenHandle))) {
         return static::throwNotFoundError();
     }
     if ($Token->isUsed) {
         return static::throwError('Token has already been used. Please try again.');
     }
     if ($Token->isExpired) {
         return static::throwError('Token has expired. Please try again.');
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         try {
             $Token->handleRequest($_REQUEST);
         } catch (Exception $e) {
             $error = $e->getMessage();
             if (!$error) {
                 throw $e;
             }
         }
     }
     $tokenClass = $Token->Class;
     return static::respond($tokenClass::$formTemplate, array('Token' => $Token, 'error' => isset($error) ? $error : false));
 }
 public static function handleRequest()
 {
     $GLOBALS['Session']->requireAuthentication();
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     return static::respond('drafts', array('success' => true, 'data' => AbstractContent::getAllByWhere(array('AuthorID' => $GLOBALS['Session']->PersonID, 'Status = "Draft" OR Published > CURRENT_TIMESTAMP'))));
 }
 public static function handleRequest()
 {
     // handle JSON requests
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     // route request
     return static::handleContactRequest();
 }
 public static function respond($responseID, $responseData = array(), $responseMode = false)
 {
     if (static::$responseMode == 'rss') {
         static::$responseMode = 'xml';
         return parent::respond('rss', $responseData);
     } else {
         return parent::respond($responseID, $responseData);
     }
 }
 public static function handleRequest()
 {
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     switch ($requestHandle = static::shiftPath()) {
         default:
             return static::handleCollectionsRequest();
     }
 }
 public static function handleRequest()
 {
     if (extension_loaded('newrelic')) {
         newrelic_disable_autorum();
     }
     // retrieve authentication attempt
     if ($GLOBALS['Session']->hasAccountLevel('Developer')) {
         $User = $GLOBALS['Session']->Person;
     } else {
         $authEngine = new \Sabre\HTTP\BasicAuth();
         $authEngine->setRealm('Develop ' . \Site::$title);
         $authUserPass = $authEngine->getUserPass();
         // try to get user
         $userClass = \User::$defaultClass;
         $User = $userClass::getByLogin($authUserPass[0], $authUserPass[1]);
         // send auth request if login is inadiquate
         if (!$User || !$User->hasAccountLevel('Developer')) {
             $authEngine->requireLogin();
             die("You must login using a " . \Site::getConfig('primary_hostname') . " account with Developer access\n");
         }
     }
     // store login to session
     if (isset($GLOBALS['Session'])) {
         $GLOBALS['Session'] = $GLOBALS['Session']->changeClass('UserSession', array('PersonID' => $User->ID));
     }
     // detect base path
     $basePath = array_slice(\Site::$requestPath, 0, count(\Site::$resolvedPath));
     // switch to JSON response mode
     if (static::peekPath() == 'json') {
         $basePath[] = static::$responseMode = static::shiftPath();
     }
     // handle /develop request
     if ($_SERVER['REQUEST_METHOD'] == 'GET' && static::getResponseMode() == 'html' && !static::peekPath()) {
         \RequestHandler::respond('app/ext', array('App' => \Sencha_App::getByName('EmergenceEditor'), 'mode' => 'production', 'title' => 'EmergenceEditor'));
     }
     // initial and configure SabreDAV
     $server = new \Sabre\DAV\Server(new RootCollection());
     $server->setBaseUri('/' . join('/', $basePath));
     // The lock manager is reponsible for making sure users don't overwrite each others changes. Change 'data' to a different
     // directory, if you're storing your data somewhere else.
     #       $lockBackend = new Sabre_DAV_Locks_Backend_FS('/tmp/dav-lock');
     #       $lockPlugin = new Sabre_DAV_Locks_Plugin($lockBackend);
     #       $server->addPlugin($lockPlugin);
     // filter temporary files
     $server->addPlugin(new \Sabre\DAV\TemporaryFileFilterPlugin('/tmp/dav-tmp'));
     // ?mount support
     $server->addPlugin(new \Sabre\DAV\Mount\Plugin());
     // emergence :)
     $server->addPlugin(new \Emergence\DAV\ServerPlugin());
     // All we need to do now, is to fire up the server
     $server->exec();
 }
 public static function handleRequest()
 {
     // save static class
     static::$calledClass = get_called_class();
     switch (static::peekPath()) {
         case 'csv':
         case 'json':
         case 'pdf':
             static::$responseMode = static::shiftPath();
             break;
     }
     return static::handleRecordsRequest();
 }
 public static function respond($responseID, $data = array())
 {
     if (static::$responseMode == 'rss') {
         static::$responseMode = 'xml';
         if (static::$browseConditions['AuthorID']) {
             $User = User::getByID(static::$browseConditions['AuthorID']);
             $data['Author'] = $User;
             $data['Link'] = 'http://' . $_SERVER['HTTP_HOST'] . '/people/' . $User->Username;
         }
         return parent::respond('rss', $data);
     } else {
         return parent::respond($responseID, $data);
     }
 }
 public static function handleRequest()
 {
     // handle json response mode
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     // handle action
     switch ($action = static::shiftPath()) {
         #			case 'media':
         #			{
         #				return static::handleMediaRequest();
         #			}
         case 'upload':
             return static::handleUploadRequest();
         case 'open':
             $mediaID = static::shiftPath();
             return static::handleMediaRequest($mediaID);
         case 'download':
             $mediaID = static::shiftPath();
             $filename = urldecode(static::shiftPath());
             return static::handleDownloadRequest($mediaID, $filename);
         case 'info':
             $mediaID = static::shiftPath();
             return static::handleInfoRequest($mediaID);
         case 'caption':
             $mediaID = static::shiftPath();
             return static::handleCaptionRequest($mediaID);
         case 'delete':
             return static::handleDeleteRequest();
         case 'thumbnail':
             return static::handleThumbnailRequest();
         case 'manage':
             return MediaManagerRequestHandler::handleRequest();
         case false:
         case '':
         case 'browse':
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 return static::handleUploadRequest();
             }
             return static::handleBrowseRequest();
         default:
             if (ctype_digit($action)) {
                 return static::handleMediaRequest($action);
             } else {
                 return parent::handleRecordsRequest($action);
             }
     }
 }
 public static function handleRequest()
 {
     // handle JSON requests
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     switch ($action = static::shiftPath()) {
         case 'recover':
             return static::handleRecoverPasswordRequest();
         case '':
         case false:
             return static::handleRegistrationRequest();
         default:
             return static::throwNotFoundException();
     }
 }
 public static function handleRequest()
 {
     if (empty(static::$recordClass)) {
         throw new Exception('static public $recordClass must be set to an ActiveRecord implementation');
     }
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     switch ($_SERVER['REQUEST_METHOD']) {
         case 'GET':
             return static::handleReadRequest();
         case 'POST':
             return static::handleCreateRequest();
         case 'PUT':
             return static::handleUpdateRequest();
         case 'DELETE':
             return static::handleDeleteRequest();
     }
 }
 public static function handleRequest()
 {
     // handle JSON requests
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     // route request
     switch ($discussionHandle = static::shiftPath()) {
         case '':
         case false:
             return static::handleBrowseRequest();
         default:
             // lookup discussion by handle
             if (!($Discussion = Discussion::getByHandle($discussionHandle))) {
                 return static::throwNotFoundError();
             }
             return static::handleDiscussionRequest($Discussion);
     }
 }
 public static function handleRequest()
 {
     // handle JSON requests
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     // route request
     switch ($forumHandle = static::shiftPath()) {
         case '':
         case false:
             return static::handleBrowseRequest();
         default:
             // lookup forum by handle
             if (!($Forum = Forum::getByHandle($forumHandle))) {
                 return static::throwNotFoundError();
             }
             return static::handleForumRequest($Forum);
     }
 }
 public static function handleRequest($returnURL = null)
 {
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     } elseif ($_REQUEST['format'] == 'json' || $_SERVER['HTTP_ACCEPT'] == 'application/json') {
         static::$responseMode = 'json';
     }
     if (static::peekPath() == 'logout') {
         return static::handleLogoutRequest($returnURL);
     }
     // force login
     $GLOBALS['Session']->requireAuthentication();
     $returnURL = static::getReturnURL($returnURL);
     if (is_callable(static::$onLoginComplete)) {
         call_user_func(static::$onLoginComplete, $GLOBALS['Session'], $returnURL);
     }
     static::onLoginComplete($GLOBALS['Session'], $returnURL);
     // respond
     return static::respond('login/loginComplete', array('success' => true, 'data' => $GLOBALS['Session'], 'returnURL' => $returnURL));
 }
 public static function handleRequest()
 {
     if (empty(static::$recordClass)) {
         throw new Exception('static public $recordClass must be set to an ActiveRecord implementation');
     }
     if (static::peekPath() == 'json') {
         static::$responseMode = static::shiftPath();
     }
     switch ($action ? $action : ($action = static::peekPath())) {
         case 'post':
             static::shiftPath();
             return static::handlePostRequest();
         case 'edit':
             static::shiftPath();
             if ($Content = CMS_BlogPost::getByID(static::peekPath())) {
                 return static::handleEditRequest($Content);
             } else {
                 return static::throwNotFoundError();
             }
         default:
             return parent::handleRequest();
     }
 }
 public static function handleAutoReserveRequest()
 {
     $GLOBALS['Session']->requireAccountLevel('Developer');
     static::$responseMode = 'json';
     $created = array();
     $failed = array();
     $verified = array();
     $dh = opendir('.');
     while (false !== ($file = readdir($dh))) {
         if (is_file($file) && preg_match('/^(.*)\\.php$/i', $file, $matches)) {
             $handle = $matches[1];
             $Existing = GlobalHandle::getByHandle($handle);
             if (!$Existing) {
                 $created[] = GlobalHandle::create(array('Type' => 'Reserve', 'Handle' => $handle), true);
             } elseif ($Existing->Type != 'Reserve') {
                 $failed[] = $Existing;
             } else {
                 $verified[] = $Existing;
             }
         }
     }
     closedir($dh);
     return static::respond('autoreserve', array('success' => true, 'created' => $created, 'failed' => $failed, 'verified' => $verified));
 }
 public static function handleTimesheetRequest()
 {
     if (static::peekPath() == 'html') {
         static::$responseMode = 'html';
     }
     $GLOBALS['Session']->requireAccountLevel('Developer');
     $daysLimit = isset($_REQUEST['daysLimit']) ? $_REQUEST['daysLimit'] : 7;
     $gapLimit = isset($_REQUEST['gapLimit']) ? $_REQUEST['gapLimit'] : 1800;
     $minimumSessionDuration = isset($_REQUEST['minimumSessionDuration']) ? $_REQUEST['minimumSessionDuration'] : 120;
     $dayShift = isset($_REQUEST['dayShift']) ? $_REQUEST['dayShift'] : 18000;
     // 5 hours
     $workDays = array();
     $editResults = DB::query('SELECT UNIX_TIMESTAMP(Timestamp) AS Timestamp, AuthorID' . ' FROM _e_files f' . ' WHERE f.AuthorID IS NOT NULL' . ' ORDER BY ID DESC');
     while ($editRecord = $editResults->fetch_assoc()) {
         $day = date('Y-m-d', $editRecord['Timestamp'] - $dayShift);
         if (!array_key_exists($day, $workDays)) {
             if (count($workDays) == $daysLimit) {
                 break;
             }
             $workDays[$day] = array();
         }
         if (!array_key_exists($editRecord['AuthorID'], $workDays[$day])) {
             $workDays[$day][$editRecord['AuthorID']] = array();
         }
         if (!count($workDays[$day][$editRecord['AuthorID']]) || $workDays[$day][$editRecord['AuthorID']][0]['firstEdit'] - $gapLimit > $editRecord['Timestamp']) {
             array_unshift($workDays[$day][$editRecord['AuthorID']], array('firstEdit' => $editRecord['Timestamp'], 'lastEdit' => $editRecord['Timestamp']));
         } else {
             $workDays[$day][$editRecord['AuthorID']][0]['firstEdit'] = $editRecord['Timestamp'];
         }
     }
     // compile results
     $results = array();
     foreach ($workDays as $day => $authors) {
         #        	print("<h1>$day</h1>");
         $dayResults = array('date' => $day, 'authors' => array());
         foreach ($authors as $authorID => $sessions) {
             $authorResults = array('Person' => Person::getByID($authorID), 'totalDuration' => 0, 'sessions' => array());
             #        		print("<h2>$Author->FullName</h2><pre>");
             foreach ($sessions as $authorSession) {
                 $authorSession['duration'] = $authorSession['lastEdit'] - $authorSession['firstEdit'];
                 $authorResults['sessions'][] = $authorSession;
                 #        			printf("%s\t->\t%s\t:\t%s minutes\n", date('g:i:sa', $authorSession['firstEdit']), date('g:i:sa', $authorSession['lastEdit']), number_format($authorSession['duration']/60,1));
                 $authorResults['totalDuration'] += max($authorSession['duration'], $minimumSessionDuration);
             }
             $dayResults['authors'][] = $authorResults;
             #        		print("</pre><p>".number_format($dayAuthor['duration'] / 60, 1)." minutes estimated total</p>");
         }
         $results[] = $dayResults;
     }
     return static::respond('timesheet', array('data' => $results, 'daysLimit' => $daysLimit, 'gapLimit' => $gapLimit, 'minimumSessionDuration' => $minimumSessionDuration, 'dayShift' => $dayShift));
 }
 public static function handleSynchronizeRequest()
 {
     // read request/response configuration
     $pretend = !empty($_REQUEST['pretend']);
     if (static::peekPath() == 'json' || static::peekPath() == 'text') {
         static::$responseMode = static::shiftPath();
     }
     if ($jobHandle = static::shiftPath()) {
         if (!($Job = Job::getByHandle($jobHandle))) {
             return static::throwNotFoundError('Job not found');
         }
         if (static::$synchronizeRequiredAccountLevel) {
             $GLOBALS['Session']->requireAccountLevel(static::$synchronizeRequiredAccountLevel);
         }
         if (static::peekPath() == 'log') {
             $logPath = $Job->getLogPath() . '.bz2';
             if (file_exists($logPath)) {
                 header('Content-Type: application/json');
                 header(sprintf('Content-Disposition: attachment; filename="%s-%u.json"', $Job->Connector, $Job->ID));
                 passthru("bzcat {$logPath}");
                 exit;
             } else {
                 return static::throwNotFoundError('Log not available');
             }
         }
         return static::respond('jobStatus', array('data' => $Job));
     }
     // authenticate and create job or copy template
     if (!empty($_REQUEST['template'])) {
         $TemplateJob = Job::getByHandle($_REQUEST['template']);
         if (!$TemplateJob || $TemplateJob->Status != 'Template' || $TemplateJob->Connector != get_called_class()) {
             return static::throwNotFoundError('Template job not found');
         }
         $Job = Job::create(array('Connector' => $TemplateJob->Connector, 'Template' => $TemplateJob, 'Config' => $TemplateJob->Config));
     } else {
         if (static::$synchronizeRequiredAccountLevel) {
             $GLOBALS['Session']->requireAccountLevel(static::$synchronizeRequiredAccountLevel);
         }
         $Job = Job::create(array('Connector' => get_called_class(), 'Config' => static::_getJobConfig($_REQUEST)));
         if (!empty($_REQUEST['createTemplate'])) {
             if ($pretend) {
                 return static::throwInvalidRequestError('Cannot combine pretend and createTemplate');
             }
             $Job->Status = 'Template';
             $Job->save();
             return static::respond('templateCreated', array('data' => $Job));
         }
     }
     // show template if not a post
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         return static::respond('createJob', array('data' => $Job, 'templates' => Job::getAllByWhere(array('Status' => 'Template', 'Connector' => get_called_class()))));
     }
     // save job in pending state before starting
     if (!$pretend) {
         $Job->save();
     }
     // close connection to client
     if (!empty($_REQUEST['fork'])) {
         header('Location: ' . static::_getConnectorBaseUrl(true) . '/' . $Job->Handle, true, 201);
         print json_encode(array('data' => $Job->getData()));
         fastcgi_finish_request();
     }
     // update execution time limit
     set_time_limit(static::$synchronizeTimeLimit);
     // execute synchronization
     try {
         $success = static::synchronize($Job, $pretend);
     } catch (Exception $e) {
         $Job->logException($e);
         $success = false;
     }
     if (!$success) {
         $Job->Status = 'Failed';
     }
     // save job if not pretend
     if (!$pretend) {
         $Job->save();
         $Job->writeLog();
         // email report
         if (!empty($Job->Config['reportTo'])) {
             \Emergence\Mailer\Mailer::sendFromTemplate($Job->Config['reportTo'], 'syncronizeComplete', array('Job' => $Job, 'connectorBaseUrl' => static::_getConnectorBaseUrl(true)));
         }
     }
     // all done, respond
     return static::respond('syncronizeComplete', array('data' => $Job, 'success' => $success, 'pretend' => $pretend));
 }
 public static function handleStageMultiRequest()
 {
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         return static::throwInvalidRequestError('Request must be POST');
     }
     if (0 === strpos($_SERVER['CONTENT_TYPE'], 'application/json')) {
         $_REQUEST = \JSON::getRequestData();
     }
     try {
         $layer = static::$_currentRepo;
     } catch (Exception $e) {
         return static::throwInvalidRequestError($e->getMessage());
     }
     static::$responseMode = 'json';
     $command = 'add';
     $success = true;
     if (is_array($_REQUEST['Files'])) {
         foreach ($_REQUEST['Files'] as $file) {
             $file = escapeshellcmd($file);
             $args = [$file];
             try {
                 $output = $layer->getGitWrapper()->run($command, $args);
                 $operations[] = ['success' => true, 'output' => $output, 'command' => $command, 'args' => $args];
             } catch (Exception $e) {
                 $success = false;
                 $operations[] = ['success' => false, 'output' => $output, 'command' => $command, 'args' => $args, 'error' => $e->getMessage()];
             }
         }
     }
     return static::respond('stage-multi', ['success' => $success, 'operations' => $operations]);
 }