/**
  * testData
  *
  * @retun void
  * 
  * @access public
  */
 function testData()
 {
     $this->assertEqual($this->Formatacao->data(), date('d/m/Y'));
     $this->assertEqual($this->Formatacao->data(strtotime('2009-04-21')), '21/04/2009');
     $this->assertEqual($this->Formatacao->data('errado', array('invalid' => 'Inválido')), 'Inválido');
     $this->assertEqual($this->Formatacao->data(strtotime('2009-04-21 00:00:00 GMT'), array('userOffset' => '-1')), '20/04/2009');
 }
Example #2
0
 /**
  * Callback called after a spec execution.
  *
  * @param object $log The log object of the whole spec.
  */
 public function specEnd($log = null)
 {
     $isOk = $log->passed() ? "ok" : "not ok";
     switch ($log->type()) {
         case 'skipped':
         case 'pending':
         case 'excluded':
             $prefix = "# {$log->type()} ";
             break;
         default:
             $prefix = '- ';
             break;
     }
     $message = $prefix . trim(implode(" ", $log->messages()));
     $this->_counter++;
     $this->write("{$isOk} {$this->_counter} {$message}\n");
     if ($exception = $log->exception()) {
         $this->write('# Exception: `' . get_class($exception) . '` Code(' . $exception->getCode() . '):' . "\n");
         $this->write('# Message: ' . $exception->getMessage() . "\n");
     } else {
         foreach ($log->children() as $log) {
             if ($log->passed()) {
                 continue;
             }
             $toString = function ($instance) {
                 return 'an instance of `' . get_class($instance) . '`';
             };
             foreach ($log->data() as $key => $value) {
                 $key = ucfirst($key);
                 $value = Text::toString($value, ['object' => ['method' => $toString]]);
                 $this->write("# {$key}: {$value}\n");
             }
         }
     }
 }
Example #3
0
 /**
  * 修改分类
  * @param   array $data 一维数组,$data需要包含要修改的分类cat_id。
  *
  * @return  boolean                 组修改成功,返回相应的分类ID,修改失败,返回FALSE;
  */
 public function edit($data)
 {
     if (empty($data)) {
         return false;
     }
     return $this->model->data($data)->save();
 }
Example #4
0
 /**
  * Set the data to update or insert.
  * 
  * @param  object $data        the data object or array
  * @param  object $skipFields  the fields to skip.
  * @access public
  * @return object the dao object self.
  */
 public function data($data, $skipFields = '')
 {
     if (!is_object($data)) {
         $data = (object) $data;
     }
     $this->sqlobj->data($data, $skipFields);
     return $this;
 }
Example #5
0
 /**
  * Set the data to update or insert.
  * 
  * @param  object $data         the data object or array
  * @access public
  * @return object the dao object self.
  */
 public function data($data)
 {
     if (!is_object($data)) {
         $data = (object) $data;
     }
     $this->sqlobj->data($data);
     return $this;
 }
Example #6
0
 /**
  * Set the data to update or insert.
  * 
  * @param  object $data        the data object or array
  * @param  object $skipFields  the fields to skip.
  * @access public
  * @return object the dao object self.
  */
 public function data($data, $skipFields = '')
 {
     if (!is_object($data)) {
         $data = (object) $data;
     }
     if ($this->autoLang and !isset($data->lang)) {
         $data->lang = $this->app->getClientLang();
     }
     $this->sqlobj->data($data, $skipFields);
     return $this;
 }
 /**
  * Set the data to update or insert.
  * 
  * @param  object $data         the data object or array
  * @param  bool   $autoCompany  auto append company field or not
  * @access public
  * @return object the dao object self.
  */
 public function data($data, $autoCompany = true)
 {
     if (!is_object($data)) {
         $data = (object) $data;
     }
     if ($autoCompany and isset($this->app->company) and $this->table != TABLE_COMPANY and !isset($data->company)) {
         $data->company = $this->app->company->id;
     }
     $this->sqlobj->data($data);
     return $this;
 }
Example #8
0
 /**
  * The session save handler callback for reading data from the session.
  *
  * @param string $key The key of the data to be returned. If no key is specified,
  *        then all session data is returned in an array of key/value pairs.
  * @return mixed Value corresponding to key if set, null otherwise.
  */
 public function _read($key = null)
 {
     if (!$this->_data || !is_object($this->_data)) {
         return null;
     }
     if ($key === null) {
         return $this->_data->data();
     }
     $data = $this->_data->{$key};
     return $data instanceof Entity ? $data->data() : $data;
 }
Example #9
0
 /**
  * Will return a find first condition on the associated model if a record is connected.
  * Called by conditions when it is called as a get and no condition is set.
  *
  * @return array ([model's primary key'] => [that key set in the record]).
  */
 protected function _entityConditions()
 {
     if (!$this->_entity || !($model = $this->_config['model'])) {
         return;
     }
     if (is_array($key = $model::key($this->_entity->data()))) {
         return $key;
     }
     $key = $model::meta('key');
     return array($key => $this->_entity->{$key});
 }
Example #10
0
 /**
  * Set the data to update or insert.
  * 
  * @param  object $data        the data object or array
  * @param  object $skipFields  the fields to skip.
  * @access public
  * @return object the dao object self.
  */
 public function data($data, $skipFields = '')
 {
     if (!is_object($data)) {
         $data = (object) $data;
     }
     if ($this->autoLang and !isset($data->lang)) {
         $data->lang = $this->app->getClientLang();
         if (RUN_MODE == 'front' and $this->app->config->cn2tw) {
             $data->lang = str_replace('zh-tw', 'zh-cn', $data->lang);
         }
     }
     $this->sqlobj->data($data, $skipFields);
     return $this;
 }
Example #11
0
 /**
  * Will return a find first condition on the associated model if a record is connected.
  * Called by conditions when it is called as a get and no condition is set.
  *
  * @return array Returns an array in the following format:
  *         `([model's primary key'] => [that key set in the record])`.
  */
 protected function _entityConditions()
 {
     if (!$this->_entity || !($model = $this->_config['model'])) {
         return;
     }
     $key = $model::key($this->_entity->data());
     if (!$key && $this->_type != "create") {
         throw new ConfigException('No matching primary key found.');
     }
     if (is_array($key)) {
         return $key;
     }
     $key = $model::meta('key');
     $val = $this->_entity->{$key};
     return $val ? array($key => $val) : array();
 }
Example #12
0
 /**
  * Implements Mail::send() function using SMTP.
  *
  * @param mixed $recipients Either a comma-seperated list of recipients
  *              (RFC822 compliant), or an array of recipients,
  *              each RFC822 valid. This may contain recipients not
  *              specified in the headers, for Bcc:, resending
  *              messages, etc.
  *
  * @param array $headers The array of headers to send with the mail, in an
  *              associative array, where the array key is the
  *              header name (e.g., 'Subject'), and the array value
  *              is the header value (e.g., 'test'). The header
  *              produced from those values would be 'Subject:
  *              test'.
  *
  * @param string $body The full text of the message body, including any
  *               MIME parts, etc.
  *
  * @return mixed Returns true on success
  */
 public function send($recipients, $headers, $body)
 {
     /* If we don't already have an SMTP object, create one. */
     $result = $this->getSMTPObject();
     if (!is_array($headers)) {
         throw new InvalidArgumentException('$headers must be an array');
     }
     $this->_sanitizeHeaders($headers);
     $headerElements = $this->prepareHeaders($headers);
     list($from, $textHeaders) = $headerElements;
     /* Since few MTAs are going to allow this header to be forged
      * unless it's in the MAIL FROM: exchange, we'll use
      * Return-Path instead of From: if it's set. */
     if (!empty($headers['Return-Path'])) {
         $from = $headers['Return-Path'];
     }
     if (!isset($from)) {
         $this->_smtp->rset();
         throw new InvalidArgumentException('No From: address has been provided', self::SMTP_ERROR_FROM);
     }
     $params = null;
     if (!empty($this->_extparams)) {
         foreach ($this->_extparams as $key => $val) {
             $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
         }
     }
     $this->_smtp->mailFrom($from, ltrim($params));
     $recipients = $this->parseRecipients($recipients);
     foreach ($recipients as $recipient) {
         $this->_smtp->rcptTo($recipient);
     }
     /* Send the message's headers and the body as SMTP data. */
     $res = $this->_smtp->data($body, $textHeaders);
     list(, $args) = $this->_smtp->getResponse();
     if (preg_match("/Ok: queued as (.*)/", $args, $queued)) {
         $this->queued_as = $queued[1];
     }
     /* we need the greeting; from it we can extract the authorative name of the mail server we've really connected to.
      * ideal if we're connecting to a round-robin of relay servers and need to track which exact one took the email */
     $this->greeting = $this->_smtp->getGreeting();
     /* If persistent connections are disabled, destroy our SMTP object. */
     if ($this->persist === false) {
         $this->disconnect();
     }
     return true;
 }
Example #13
0
 /**
  * Implements Mail::send() function using SMTP.
  *
  * @param mixed $recipients Either a comma-seperated list of recipients
  *              (RFC822 compliant), or an array of recipients,
  *              each RFC822 valid. This may contain recipients not
  *              specified in the headers, for Bcc:, resending
  *              messages, etc.
  *
  * @param array $headers The array of headers to send with the mail, in an
  *              associative array, where the array key is the
  *              header name (e.g., 'Subject'), and the array value
  *              is the header value (e.g., 'test'). The header
  *              produced from those values would be 'Subject:
  *              test'.
  *
  * @param string $body The full text of the message body, including any
  *               MIME parts, etc.
  *
  * @return mixed Returns true on success, or a PEAR_Error
  *               containing a descriptive error message on
  *               failure.
  * @access public
  */
 function send($recipients, $headers, $body)
 {
     /* If we don't already have an SMTP object, create one. */
     $result =& $this->getSMTPObject();
     if (PEAR::isError($result)) {
         return $result;
     }
     if (!is_array($headers)) {
         return PEAR::raiseError('$headers must be an array');
     }
     $this->_sanitizeHeaders($headers);
     $headerElements = $this->prepareHeaders($headers);
     if (is_a($headerElements, 'PEAR_Error')) {
         $this->_smtp->rset();
         return $headerElements;
     }
     list($from, $textHeaders) = $headerElements;
     /* Since few MTAs are going to allow this header to be forged
      * unless it's in the MAIL FROM: exchange, we'll use
      * Return-Path instead of From: if it's set. */
     if (!empty($headers['Return-Path'])) {
         $from = $headers['Return-Path'];
     }
     if (!isset($from)) {
         $this->_smtp->rset();
         return PEAR::raiseError('No From: address has been provided', PEAR_MAIL_SMTP_ERROR_FROM);
     }
     $params = null;
     if (!empty($this->_extparams)) {
         foreach ($this->_extparams as $key => $val) {
             $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
         }
     }
     if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
         $error = $this->_error("Failed to set sender: {$from}", $res);
         $this->_smtp->rset();
         return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
     }
     $recipients = $this->parseRecipients($recipients);
     if (is_a($recipients, 'PEAR_Error')) {
         $this->_smtp->rset();
         return $recipients;
     }
     foreach ($recipients as $recipient) {
         $res = $this->_smtp->rcptTo($recipient);
         if (is_a($res, 'PEAR_Error')) {
             $error = $this->_error("Failed to add recipient: {$recipient}", $res);
             $this->_smtp->rset();
             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
         }
     }
     /* Send the message's headers and the body as SMTP data. */
     $res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body);
     if (is_a($res, 'PEAR_Error')) {
         $error = $this->_error('Failed to send data', $res);
         $this->_smtp->rset();
         return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
     }
     /* If persistent connections are disabled, destroy our SMTP object. */
     if ($this->persist === false) {
         $this->disconnect();
     }
     return true;
 }
Example #14
0
 /**
  * After an authentication query against the configured model class has occurred, this method
  * iterates over the configured validators and checks each one by passing the submitted form
  * value as the first parameter, and the corresponding database value as the second. The
  * validator then returns a boolean to indicate success. If the validator fails, it will cause
  * the entire authentication operation to fail. Note that any filters applied to a form field
  * will affect the data passed to the validator.
  *
  * @see lithium\security\auth\adapter\Form::__construct()
  * @see lithium\security\auth\adapter\Form::$_validators
  * @param object $user The user object returned from the database. This object must support a
  *               `data()` method, which returns the object's array representation, and
  *               also returns individual field values by name.
  * @param array $data The form data submitted in the request and passed to `Form::check()`.
  * @return array Returns an array of authenticated user data on success, otherwise `false` if
  *               any of the configured validators fails. See `'validators'` in the `$config`
  *               parameter of `__construct()`.
  */
 protected function _validate($user, array $data)
 {
     foreach ($this->_validators as $field => $validator) {
         if (!isset($this->_fields[$field]) || $field === 0) {
             continue;
         }
         if (!is_callable($validator)) {
             $message = "Authentication validator for `{$field}` is not callable.";
             throw new UnexpectedValueException($message);
         }
         $field = $this->_fields[$field];
         $value = isset($data[$field]) ? $data[$field] : null;
         if (!call_user_func($validator, $value, $user->data($field))) {
             return false;
         }
     }
     $user = $user->data();
     if (!isset($this->_validators[0])) {
         return $user;
     }
     if (!is_callable($this->_validators[0])) {
         throw new UnexpectedValueException("Authentication validator is not callable.");
     }
     return call_user_func($this->_validators[0], $data, $user) ? $user : false;
 }
Example #15
0
 /**
  * Builds a Cookie header value.
  *
  * @param  string $name   The cookie name.
  * @param  object $cookie The cookie instance.
  * @return string
  */
 protected static function _cookieValue($name, $cookie)
 {
     if (!Cookie::isValidName($name)) {
         throw new Exception("Invalid cookie name `'{$name}'`.");
     }
     $result = [];
     foreach ($cookie->data() as $value) {
         $result[] = $name . '=' . urlencode($value);
     }
     return join('; ', $result);
 }
Example #16
0
 /**
  * Implements Mail::send() function using SMTP.
  *
  * @param mixed $recipients Either a comma-seperated list of recipients
  *              (RFC822 compliant), or an array of recipients,
  *              each RFC822 valid. This may contain recipients not
  *              specified in the headers, for Bcc:, resending
  *              messages, etc.
  *
  * @param array $headers The array of headers to send with the mail, in an
  *              associative array, where the array key is the
  *              header name (e.g., 'Subject'), and the array value
  *              is the header value (e.g., 'test'). The header
  *              produced from those values would be 'Subject:
  *              test'.
  *
  * @param string $body The full text of the message body, including any
  *               MIME parts, etc.
  *
  * @return mixed Returns true on success, or a PEAR_Error
  *               containing a descriptive error message on
  *               failure.
  * @access public
  */
 function send($recipients, $headers, $body)
 {
     /* If we don't already have an SMTP object, create one. */
     $result =& $this->getSMTPObject();
     if (PEAR::isError($result)) {
         return $result;
     }
     if (!is_array($headers)) {
         return PEAR::raiseError('$headers must be an array');
     }
     $this->_sanitizeHeaders($headers);
     $headerElements = $this->prepareHeaders($headers);
     if (is_a($headerElements, 'PEAR_Error')) {
         $this->_smtp->rset();
         return $headerElements;
     }
     list($from, $textHeaders) = $headerElements;
     /* Since few MTAs are going to allow this header to be forged
      * unless it's in the MAIL FROM: exchange, we'll use
      * Return-Path instead of From: if it's set. */
     if (!empty($headers['Return-Path'])) {
         $from = $headers['Return-Path'];
     }
     if (!isset($from)) {
         $this->_smtp->rset();
         return PEAR::raiseError('No From: address has been provided', PEAR_MAIL_SMTP_ERROR_FROM);
     }
     $params = null;
     if (!empty($this->_extparams)) {
         foreach ($this->_extparams as $key => $val) {
             $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
         }
     }
     if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
         $error = $this->_error("Failed to set sender: {$from}", $res);
         $this->_smtp->rset();
         return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
     }
     $recipients = $this->parseRecipients($recipients);
     if (is_a($recipients, 'PEAR_Error')) {
         $this->_smtp->rset();
         return $recipients;
     }
     foreach ($recipients as $recipient) {
         $res = $this->_smtp->rcptTo($recipient);
         if (is_a($res, 'PEAR_Error')) {
             $error = $this->_error("Failed to add recipient: {$recipient}", $res);
             $this->_smtp->rset();
             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
         }
     }
     /* Send the message's headers and the body as SMTP data. */
     $res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body);
     list(, $args) = $this->_smtp->getResponse();
     if (preg_match("/Ok: queued as (.*)/", $args, $queued)) {
         $this->queued_as = $queued[1];
     }
     /* we need the greeting; from it we can extract the authorative name of the mail server we've really connected to.
      * ideal if we're connecting to a round-robin of relay servers and need to track which exact one took the email */
     $this->greeting = $this->_smtp->getGreeting();
     if (is_a($res, 'PEAR_Error')) {
         $error = $this->_error('Failed to send data', $res);
         $this->_smtp->rset();
         return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
     }
     /* If persistent connections are disabled, destroy our SMTP object. */
     if ($this->persist === false) {
         $this->disconnect();
     }
     return true;
 }
Example #17
0
 /**
  * Implements Mail::send() function using SMTP.
  *
  * @param mixed $recipients Either a comma-seperated list of recipients
  *              (RFC822 compliant), or an array of recipients,
  *              each RFC822 valid. This may contain recipients not
  *              specified in the headers, for Bcc:, resending
  *              messages, etc.
  *
  * @param array $headers The array of headers to send with the mail, in an
  *              associative array, where the array key is the
  *              header name (e.g., 'Subject'), and the array value
  *              is the header value (e.g., 'test'). The header
  *              produced from those values would be 'Subject:
  *              test'.
  *
  * @param string $body The full text of the message body, including any
  *               Mime parts, etc.
  *
  * @return mixed Returns true on success, or a PEAR_Error
  *               containing a descriptive error message on
  *               failure.
  * @access public
  */
 function send($recipients, $headers, $body)
 {
     include_once 'Net/SMTP.php';
     /* If we don't already have an SMTP object, create one. */
     if (is_object($this->_smtp) === false) {
         $this->_smtp = new Net_SMTP($this->host, $this->port, $this->localhost);
         /* If we still don't have an SMTP object at this point, fail. */
         if (is_object($this->_smtp) === false) {
             return PEAR::raiseError('Failed to create a Net_SMTP object', PEAR_MAIL_SMTP_ERROR_CREATE);
         }
         /* Configure the SMTP connection. */
         if ($this->debug) {
             $this->_smtp->setDebug(true);
         }
         /* Attempt to connect to the configured SMTP server. */
         if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
             $error = $this->_error('Failed to connect to ' . $this->host . ':' . $this->port, $res);
             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
         }
         /* Attempt to authenticate if authentication has been enabled. */
         if ($this->auth) {
             $method = is_string($this->auth) ? $this->auth : '';
             if (PEAR::isError($res = $this->_smtp->auth($this->username, $this->password, $method))) {
                 $error = $this->_error("{$method} authentication failure", $res);
                 $this->_smtp->rset();
                 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
             }
         }
     }
     $this->_sanitizeHeaders($headers);
     $headerElements = $this->prepareHeaders($headers);
     if (PEAR::isError($headerElements)) {
         $this->_smtp->rset();
         return $headerElements;
     }
     list($from, $textHeaders) = $headerElements;
     /* Since few MTAs are going to allow this header to be forged
      * unless it's in the MAIL FROM: exchange, we'll use
      * Return-Path instead of From: if it's set. */
     if (!empty($headers['Return-Path'])) {
         $from = $headers['Return-Path'];
     }
     if (!isset($from)) {
         $this->_smtp->rset();
         return PEAR::raiseError('No From: address has been provided', PEAR_MAIL_SMTP_ERROR_FROM);
     }
     $args['verp'] = $this->verp;
     if (PEAR::isError($res = $this->_smtp->mailFrom($from, $args))) {
         $error = $this->_error("Failed to set sender: {$from}", $res);
         $this->_smtp->rset();
         return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
     }
     $recipients = $this->parseRecipients($recipients);
     if (PEAR::isError($recipients)) {
         $this->_smtp->rset();
         return $recipients;
     }
     foreach ($recipients as $recipient) {
         if (PEAR::isError($res = $this->_smtp->rcptTo($recipient))) {
             $error = $this->_error("Failed to add recipient: {$recipient}", $res);
             $this->_smtp->rset();
             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
         }
     }
     /* Send the message's headers and the body as SMTP data. */
     if (PEAR::isError($res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body))) {
         $error = $this->_error('Failed to send data', $res);
         $this->_smtp->rset();
         return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
     }
     /* If persistent connections are disabled, destroy our SMTP object. */
     if ($this->persist === false) {
         $this->disconnect();
     }
     return true;
 }
Example #18
0
 /**
  * return entity data, filtered by top-level keys
  *
  * return only subset of data, that is requested, as in $keys or as fallback taken from
  * a static property of the corresponding model, named `$_publicFields`.
  *
  * @todo allow filtering with sub-keys, i.e. parent.sub
  * @param object $entity instance of current Record
  * @param string $key an array with all keys to be preserved, everything else is removed
  * @return array only data, that is left after filtering everything, that is not in $keys
  */
 public function publicData($entity, $keys = array())
 {
     $keys = empty($keys) && isset(static::$_publicFields) ? static::$_publicFields : (array) $keys;
     $data = $entity->data();
     foreach ($data as $key => $item) {
         if (!in_array($key, $keys)) {
             unset($data[$key]);
         }
     }
     return $data;
 }
Example #19
0
 /**
  * Returns the current position number of an element at the same level,
  * where 0 is first position
  *
  * @param object $entity the entity node to get the position from.
  * @param integer $childrenCount number of children of entity's parent,
  *        performance parameter to avoid double select.
  */
 protected function _getPosition($entity, $childrenCount = false)
 {
     extract($this->_config);
     $parent = $this->_getById($entity->{$parent});
     if ($entity->{$left} === $parent->{$left} + 1) {
         return 0;
     }
     if ($entity->{$right} + 1 === $parent->{$right}) {
         if ($childrenCount === false) {
             $childrenCount = $parent->childrens(false, 'count');
         }
         return $childrenCount - 1;
     }
     $count = 0;
     $children = $parent->childrens(false);
     $id = $entity->data($model::key());
     foreach ($children as $child) {
         if ($child->data($model::key()) === $id) {
             return $count;
         }
         $count++;
     }
     return false;
 }
Example #20
0
 /**
  * Add a score based of amount of image seller provides
  * 
  * @return void
  */
 protected function imageCount()
 {
     $this->score += $this->store['image_count'] * $this->config->data()['imageCount'];
 }
Example #21
0
 /**
  * Implements Mail::send() function using SMTP direct delivery
  *
  * @access public
  * @param mixed $recipients in RFC822 style or array
  * @param array $headers The array of headers to send with the mail.
  * @param string $body The full text of the message body,
  * @return mixed Returns true on success, or a PEAR_Error
  */
 function send($recipients, $headers, $body)
 {
     if (!is_array($headers)) {
         return PEAR::raiseError('$headers must be an array');
     }
     $result = $this->_sanitizeHeaders($headers);
     if (is_a($result, 'PEAR_Error')) {
         return $result;
     }
     // Prepare headers
     $headerElements = $this->prepareHeaders($headers);
     if (is_a($headerElements, 'PEAR_Error')) {
         return $headerElements;
     }
     list($from, $textHeaders) = $headerElements;
     // use 'Return-Path' if possible
     if (!empty($headers['Return-Path'])) {
         $from = $headers['Return-Path'];
     }
     if (!isset($from)) {
         return $this->_raiseError('no_from');
     }
     // Prepare recipients
     $recipients = $this->parseRecipients($recipients);
     if (is_a($recipients, 'PEAR_Error')) {
         return $recipients;
     }
     foreach ($recipients as $rcpt) {
         list($user, $host) = explode('@', $rcpt);
         $mx = $this->_getMx($host);
         if (is_a($mx, 'PEAR_Error')) {
             return $mx;
         }
         if (empty($mx)) {
             $info = array('rcpt' => $rcpt);
             return $this->_raiseError('no_mx', $info);
         }
         $connected = false;
         foreach ($mx as $mserver => $mpriority) {
             $this->_smtp = new Net_SMTP($mserver, $this->port, $this->mailname);
             // configure the SMTP connection.
             if ($this->debug) {
                 $this->_smtp->setDebug(true);
             }
             // attempt to connect to the configured SMTP server.
             $res = $this->_smtp->connect($this->timeout);
             if (is_a($res, 'PEAR_Error')) {
                 $this->_smtp = null;
                 continue;
             }
             // connection established
             if ($res) {
                 $connected = true;
                 break;
             }
         }
         if (!$connected) {
             $info = array('host' => implode(', ', array_keys($mx)), 'port' => $this->port, 'rcpt' => $rcpt);
             return $this->_raiseError('not_connected', $info);
         }
         // Verify recipient
         if ($this->vrfy) {
             $res = $this->_smtp->vrfy($rcpt);
             if (is_a($res, 'PEAR_Error')) {
                 $info = array('rcpt' => $rcpt);
                 return $this->_raiseError('failed_vrfy_rcpt', $info);
             }
         }
         // mail from:
         $args['verp'] = $this->verp;
         $res = $this->_smtp->mailFrom($from, $args);
         if (is_a($res, 'PEAR_Error')) {
             $info = array('from' => $from);
             return $this->_raiseError('failed_set_from', $info);
         }
         // rcpt to:
         $res = $this->_smtp->rcptTo($rcpt);
         if (is_a($res, 'PEAR_Error')) {
             $info = array('rcpt' => $rcpt);
             return $this->_raiseError('failed_set_rcpt', $info);
         }
         // Don't send anything in test mode
         if ($this->test) {
             $result = $this->_smtp->rset();
             $res = $this->_smtp->rset();
             if (is_a($res, 'PEAR_Error')) {
                 return $this->_raiseError('failed_rset');
             }
             $this->_smtp->disconnect();
             $this->_smtp = null;
             return true;
         }
         // Send data
         $res = $this->_smtp->data("{$textHeaders}\r\n{$body}");
         if (is_a($res, 'PEAR_Error')) {
             $info = array('rcpt' => $rcpt);
             return $this->_raiseError('failed_send_data', $info);
         }
         $this->_smtp->disconnect();
         $this->_smtp = null;
     }
     return true;
 }
Example #22
0
 /**
  * Get the geocode latitude/longitude points from given address.
  * Look in the cache first, otherwise get from web service (i.e. Google or Yahoo!).
  * 
  * @param object $entity A `Record` or `Document` object containing the address data to be
  *               geocoded.
  */
 public static function geocode($entity)
 {
     if (!isset(static::$_configurations[$class = $entity->model()])) {
         return null;
     }
     $config = static::$_configurations[$class];
     $geocoder = static::$_classes['geocoder'];
     $data = Set::flatten($entity->data());
     $address = trim(String::insert($config['format'], $data));
     return $address ? $geocoder::find($config['service'], $address) : null;
 }
Example #23
0
 /**
  * Builds a Set-Cookie header value.
  *
  * @param  string $name   The cookie name.
  * @param  object $cookie The cookie instance.
  * @return string
  */
 protected static function _setCookieValue($name, $cookie)
 {
     if (!Cookie::isValidName($name)) {
         throw new Exception("Invalid Set-Cookie name `'{$name}'`.");
     }
     $data = $cookie->data();
     $parts = [];
     $parts[] = $name . '=' . rawurlencode($data['value']);
     if (isset($data['max-age'])) {
         $parts[] = 'Max-Age=' . (string) $data['max-age'];
     } elseif (isset($data['expires'])) {
         $parts[] = 'Expires=' . gmdate('D, d M Y H:i:s \\G\\M\\T', $data['expires']);
     }
     if ($data['path']) {
         $parts[] = 'Path=' . $data['path'];
     }
     if ($data['domain']) {
         $parts[] = 'Domain=' . $data['domain'];
     }
     if ($data['secure']) {
         $parts[] = 'Secure';
     }
     if ($data['httponly']) {
         $parts[] = 'HttpOnly';
     }
     return join('; ', $parts);
 }
Example #24
0
 /**
  * Renders the fields SQL fragment for queries.
  *
  * @see lithium\data\source\Database::fields()
  * @param string $type Type of query i.e. `'create'` or `'update'`.
  * @param object $context Generally a `data\model\Query` instance.
  * @param array $fields
  * @param array $schema An array defining the schema of the fields used in the criteria.
  * @return string|array
  */
 protected function _fieldsReturn($type, $context, $fields, $schema)
 {
     if ($type === 'create' || $type === 'update') {
         $data = $context->data();
         if (isset($data['data']) && is_array($data['data']) && count($data) === 1) {
             $data = $data['data'];
         }
         if ($fields && is_array($fields) && is_int(key($fields))) {
             $data = array_intersect_key($data, array_combine($fields, $fields));
         }
         $method = "_{$type}Fields";
         return $this->{$method}($data, $schema, $context);
     }
     return empty($fields) ? '*' : join(', ', $fields);
 }
Example #25
0
 /**
  * @brief Antes de borrar el registro, borra los archivos.
  * @param array $cid Arreglo de los ID's a borrar
  * @param object $model Modelo que se usa para obtener los registros
  * @return bool
  */
 function __removeFile($cid, &$model)
 {
     jimport('joomla.filesystem.file');
     $folder = JPATH_SITE . $this->_folder;
     foreach ($cid as $id) {
         $record = $model->data("*", $id, 'id', true);
         foreach ($this->_fileFields as $field => $config) {
             $file = $record->{$field};
             if (JFile::exists($folder . $file)) {
                 if (!JFile::delete($folder . $file)) {
                     $this->setRedirect($this->getURLBase(), JText::_('ERROR_DELETE_FILE'), 'error');
                     return false;
                 }
             }
         }
     }
     return true;
 }
Example #26
0
 /**
  * This method generates a new version.
  *
  * It creates a duplication of the object, to allow restoring. It marks all prior
  * versions as `outdated` and the new one as `active`.
  *
  * You probably want to create a new version of an entity, whenever save is called. To achieve
  * this, you have to take care, all data is set into the entity and Versions::add with updated
  * entity is called.
  *
  * In the following example you can see, how a meta-field, `versions` is used, to decide if
  * a version needs to be created, or not.
  *
  * {{{
  *	public function save($entity, $data = array(), array $options = array()) {
  *		if (!empty($data)) {
  *			$entity->set($data);
  *		}
  *		if (!isset($options['callbacks']) || $options['callbacks'] !== false) {
  *			$versions = static::meta('versions');
  *			if (($versions === true) || (is_callable($versions) && $versions($entity, $options))) {
  *				$version_id = Versions::add($entity, $options);
  *				if ($version_id) {
  *					$entity->set(compact('version_id'));
  *				}
  *			}
  *		}
  *		return parent::save($entity, null, $options);
  *	}
  * }}}
  *
  * You have to set `versions` to true, in meta like this:
  *
  * {{{
  *  $model::meta('versions', true);
  * // OR
  *  static::meta('versions', function($entity, $options){
  *		return (bool) Environment::is('production');
  *	});
  * }}}
  *
  * @param object $entity the instance, that needs to created a new version for
  * @param array $options additional options
  * @filter
  */
 public static function add($entity, array $options = array())
 {
     $defaults = array('force' => false);
     $options += $defaults;
     $params = compact('entity', 'options');
     return static::_filter(__METHOD__, $params, function ($self, $params) {
         extract($params);
         $model = $entity->model();
         if ($model == $self || !$entity->exists()) {
             return false;
         }
         $key = $model::meta('key');
         $foreign_id = (string) $entity->{$key};
         $export = $entity->export();
         $updated = Set::diff($self::cleanData($export['update']), $self::cleanData($export['data']));
         if (empty($updated)) {
             if (!$options['force']) {
                 return false;
             }
             $updated = $entity->data();
         }
         $self::update(array('status' => 'outdated'), compact('model', 'foreign_id'));
         $data = array('model' => $model, 'foreign_id' => $foreign_id, 'status' => 'active', 'name' => (string) $entity->title(), 'fields' => $updated, 'data' => json_encode($entity->data()), 'created' => time());
         $version = $self::create($data);
         if (!$version->save()) {
             return false;
         }
         return $version->id();
     });
 }