/**
  * @see sfTask
  */
 protected function executeTask($env, $arguments = array(), $options = array())
 {
     /**
      * Getting the directory where the emails are stored
      */
     $inboxUser = sfConfig::get('app_emailToInbox_inboxUser');
     $emailDomain = sfConfig::get('app_emailToInbox_mailServerDomain');
     $newEmailPath = $arguments['emailFileAbsolutePath'];
     // there are some regular Plancake inbox email address that are
     // use just for spam
     $spamAccounts = array();
     $spamAccounts[] = 'niki_5436';
     // this will be interpreted as inbox_niki_5436@plancakebox.com
     $spamAccounts[] = 'niki.jones_15c522';
     $this->log('');
     $this->log('');
     $this->log("parsing the email at " . $newEmailPath);
     $mailParser = new PlancakeEmailParser(file_get_contents($newEmailPath));
     $plancakeSubjectOK = false;
     $plancakeRecipientOK = false;
     $emailTo = array();
     $emailSubject = '';
     $emailCc = $mailParser->getCc();
     try {
         $emailTo = $mailParser->getTo();
     } catch (Exception $e) {
         $this->handleFault("couldn't retrieve the 'to' header of the email", $newEmailPath);
         return;
     }
     try {
         $emailSubject = $mailParser->getSubject();
         $plancakeSubjectOK = true;
         $this->log("got the subject of the email: " . $emailSubject);
     } catch (Exception $e) {
         $this->handleFault("couldn't retrieve the subject of the email", $newEmailPath);
         return;
     }
     $emailRecipients = array_merge($emailTo, $emailCc);
     $emailRecipients = implode(', ', $emailRecipients);
     $deliveredToHeader = $mailParser->getHeader('Delivered-To');
     $emailRecipients = $deliveredToHeader . ', ' . $emailRecipients;
     $this->log("all recipients of the email: " . $emailRecipients);
     $internalEmail = false;
     // to flag an email sent to the catchall address
     $spamEmail = false;
     if (preg_match('/' . $inboxUser . "@{$emailDomain}/", $emailRecipients, $matches)) {
         $internalEmail = true;
         $this->log("discarding the email as it is an internal one");
         if (is_file($newEmailPath)) {
             unlink($newEmailPath);
         }
         return;
     }
     if (preg_match("/inbox_([^@]+)@{$emailDomain}/i", $emailRecipients, $matches)) {
         // found Plancake Inbox address!
         $plancakeInbox = $matches[1];
         if (in_array($plancakeInbox, $spamAccounts)) {
             $spamEmail = true;
             $this->handleFault("discarding the email because it is from a spammer", $newEmailPath);
             return;
         } else {
             $emailRecipient = 'inbox_' . $plancakeInbox . "@{$emailDomain}";
             $plancakeRecipientOK = true;
             $this->log("got the Plancake recipient of the email: " . $emailRecipient);
         }
     } else {
         $this->handleFault("couldn't find a Plancake recipient for the email", $newEmailPath);
         return;
     }
     /**
      * Sorting the email into the database
      */
     if ($plancakeRecipientOK && $plancakeSubjectOK) {
         $this->log('well done. For this email we got both the recipient and the subject. I can now create the task for the user.');
         $emailRecipientWithoutDomain = str_replace("@{$emailDomain}", '', $emailRecipient);
         $c = new Criteria();
         $c->add(PcPlancakeEmailAddressPeer::EMAIL, $emailRecipientWithoutDomain, Criteria::EQUAL);
         $plancakeEmail = PcPlancakeEmailAddressPeer::doSelectOne($c);
         if (is_object($plancakeEmail)) {
             // everything's OK
             $userId = $plancakeEmail->getUserId();
             $user = PcUserPeer::retrieveByPk($userId);
             PcUserPeer::setLoggedInUser($user);
             // check whether there is a note for the task
             $note = $this->extractNote($mailParser->getPlainBody());
             if (strlen($note)) {
                 $this->log("note: {$note}");
             }
             if (!strlen($emailSubject)) {
                 $emailSubject = 'Something went wrong with a task you sent via email. Please contact us.';
             }
             PcTaskPeer::createOrEdit($emailSubject, $user->getInbox()->getId(), 0, '', false, $note);
             $this->log('the email has successfully become a task for the user.');
         } else {
             // something wrong
             $this->handleFault('no email user', $newEmailPath);
             $this->log('couldn\'t create a task from the email - the Plancake address is not in the system :-(.');
         }
     } else {
         if ((!$plancakeRecipientOK || !$plancakeSubjectOK) && !$internalEmail && !$spamEmail) {
             // something wrong
             $this->handleFault('email parsing', $newEmailPath);
             $this->log("counldn't find both the recipient and the subject of the email. Nothing to do.");
         }
     }
     $this->log("deleting the email from the hard disk.");
     if (is_file($newEmailPath)) {
         unlink($newEmailPath);
     }
     $this->log('');
     $this->log('');
 }
Ejemplo n.º 2
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     // for performance reasons, we insert this configuration inside the method itself
     $methods = array('getToken', 'getServerTime', 'getUserSettings', 'getLists', 'getDeletedLists', 'getTags', 'getDeletedTags', 'getRepetitions', 'getRepetitionOptions', 'getTasks', 'getDeletedTasks', 'completeTask', 'uncompleteTask', 'deleteTask', 'addTask', 'editTask', 'setTaskNote', 'sync', 'whatHasChanged');
     // token, sig, api_ver are required for each method
     $extraRequiredParamsMap = array('getToken' => array('api_key'), 'getServerTime' => array(), 'getUserSettings' => array(), 'getLists' => array(), 'getDeletedLists' => array('from_ts', 'to_ts'), 'getTags' => array(), 'getDeletedTags' => array('from_ts', 'to_ts'), 'getRepetitions' => array(), 'getRepetitionOptions' => array(), 'getTasks' => array(), 'getDeletedTasks' => array('from_ts', 'to_ts'), 'completeTask' => array('task_id'), 'uncompleteTask' => array('task_id'), 'addTask' => array('descr'), 'editTask' => array('task_id'), 'setTaskNote' => array('task_id', 'note'), 'deleteTask' => array('task_id'), 'sync' => array('local_changes'), 'whatHasChanged' => array('from_ts', 'to_ts'));
     $optionalParamsMap = array('getToken' => array('user_key', 'user_email', 'user_pwd', 'extra_info'), 'getServerTime' => array(), 'getUserSettings' => array(), 'getLists' => array('from_ts', 'to_ts'), 'getDeletedLists' => array(), 'getTags' => array('from_ts', 'to_ts'), 'getDeletedTags' => array(), 'getRepetitions' => array('from_ts', 'to_ts'), 'getRepetitionOptions' => array('from_ts', 'to_ts'), 'getTasks' => array('from_ts', 'to_ts', 'task_id', 'list_id', 'tag_id', 'completed', 'only_with_due_date', 'only_without_due_date', 'only_due_today_or_tomorrow', 'only_starred', 'by_date', 'search_query'), 'getDeletedTasks' => array(), 'completeTask' => array('baseline_due_date'), 'uncompleteTask' => array(), 'addTask' => array('list_id', 'is_header', 'due_date', 'due_time', 'is_starred', 'repetition_id', 'repetition_param', 'repetition_ical_rrule', 'note', 'tag_ids'), 'editTask' => array('list_id', 'descr', 'is_header', 'due_date', 'due_time', 'is_starred', 'repetition_id', 'repetition_param', 'repetition_ical_rrule', 'note', 'tag_ids'), 'setTaskNote' => array(), 'deleteTask' => array(), 'sync' => array(), 'whatHasChanged' => array());
     $methodName = $request->getParameter('method_name');
     $token = $request->getParameter('token');
     $sig = $request->getParameter('sig');
     $apiVersion = $request->getParameter('api_ver');
     if (!in_array($methodName, $methods)) {
         return $this->returnError(PlancakeApiServer::INVALID_METHOD_ERROR);
     }
     $this->methodName = $methodName;
     if ($token === null) {
         return $this->returnError(PlancakeApiServer::MISSING_TOKEN_ERROR);
     }
     if (!$sig) {
         return $this->returnError(PlancakeApiServer::MISSING_SIGNATURE_ERROR);
     }
     if (!$apiVersion) {
         return $this->returnError(PlancakeApiServer::MISSING_API_VERSION);
     }
     $params = array();
     $params['token'] = $token;
     $params['sig'] = $sig;
     $params['api_ver'] = $apiVersion;
     $extraRequiredParams = $extraRequiredParamsMap[$methodName];
     foreach ($extraRequiredParams as $extraRequiredParam) {
         $paramValue = $request->getParameter($extraRequiredParam);
         if ($paramValue !== null) {
             $params[$extraRequiredParam] = $paramValue;
         } else {
             return $this->returnError(PlancakeApiServer::MISSING_PARAMETER_ERROR);
         }
     }
     if (!$this->isTokenValid($token)) {
         return $this->returnError(PlancakeApiServer::INVALID_TOKEN_ERROR);
     }
     $apiKey = isset($params['api_key']) ? $params['api_key'] : null;
     $apiApp = $this->getApiApp($params['token'], $apiKey);
     if ($apiApp === null) {
         return $this->returnError(PlancakeApiServer::INVALID_API_KEY_OR_TOKEN_ERROR);
     }
     if ($apiApp->isLimited()) {
         if ($apiApp->hasReachedLimits()) {
             return $this->returnError(PlancakeApiServer::RATE_LIMIT_REACHED);
         }
     }
     $apiSecret = $apiApp->getApiSecret();
     // loading optional params
     $optionalParams = $optionalParamsMap[$methodName];
     foreach ($optionalParams as $optionalParam) {
         $paramValue = $request->getParameter($optionalParam);
         if ($paramValue !== null) {
             $params[$optionalParam] = $paramValue;
         }
     }
     // if from_ts is specified, also to_ts
     if (isset($params['from_ts']) && !isset($params['to_ts']) || isset($params['to_ts']) && !isset($params['from_ts']) || isset($params['from_ts']) && isset($params['from_ts']) && !((int) $params['from_ts'] > 0) || isset($params['from_ts']) && isset($params['from_ts']) && !((int) $params['to_ts'] > 0)) {
         return $this->returnError(PlancakeApiServer::MISSING_FROMTS_OR_TOTS_PARAMETER_ERROR);
     }
     if (!(strlen($apiSecret) > 0)) {
         return $this->returnError(PlancakeApiServer::INVALID_API_KEY_ERROR);
     }
     if (!$this->isSignatureValid($params, $apiSecret)) {
         return $this->returnError(PlancakeApiServer::INVALID_SIGNATURE_ERROR);
     }
     $user = null;
     if (strlen($token) > 0) {
         $userId = PcApiTokenPeer::retrieveByPK($token)->getUserId();
         $user = PcUserPeer::retrieveByPK($userId);
         PcUserPeer::setLoggedInUser($user);
         $user->refreshLastLogin()->save();
     }
     unset($params['token']);
     unset($params['sig']);
     $response = call_user_func(array('PlancakeApiServer', $methodName), $params);
     $jsonResponse = json_encode($response);
     $apiApp->recordStats(strlen($jsonResponse));
     if ($user && $user->hasGoogleCalendarIntegrationActive()) {
         $gcalRecord = PcGoogleCalendarPeer::retrieveByUser($user);
         if ($gcalRecord && time() - $gcalRecord->getLatestSyncEndTimestamp() > sfConfig::get('app_api_googleCalendarSyncMinInterval')) {
             $gcal = new GoogleCalendarInterface($user);
             $gcal->init();
             $gcal->syncPlancake();
         }
     }
     if ($callback = $request->getParameter('callback')) {
         $this->getResponse()->setContentType('text/javascript');
         $response = $callback . '(' . $jsonResponse . ')';
     } else {
         $this->getResponse()->setContentType('application/json');
         $response = $jsonResponse;
     }
     return $this->renderText($response);
 }