public static function call($action, $parameters = null) { $ch = curl_init(YouniqueAPIURL . $action); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (YOUNIQUE_TESTSERVER) { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 100); curl_setopt($ch, CURLOPT_TIMEOUT, 100); } else { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 20); } curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-YNQ-NOSESSION: true')); if (!empty($parameters)) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); } $result = curl_exec($ch); curl_close($ch); $object = json_decode($result); if (is_object($object) && (!empty($object->result) || is_array($object->result))) { return $object->result; } else { /** * Results of exception viewable in log and error page. * Development only @see younique_api.ctp */ if (YOUNIQUE_TESTSERVER) { CakeLog::debug('API Error Action: ' . $action); CakeLog::debug(var_export($result, true)); } throw new YouniqueApiException(array('http_result' => $result, 'http_action' => $action)); } }
/** * Starts a new background task by passing some data to it with a priority * * @param string $taskName name of the task to be executed * @param mixed $data info to be passed to background task * @param sting $priority null for normal or either "low" or "high" * @return boolean success **/ public static function execute($taskName, $data = null, $priority = null) { if (!empty($priority)) { $priority = strtolower($priority); if (!in_array($priority, array('low', 'high'))) { throw new InvalidArgumentException(sprintf('%s is not a valid priority, only accepting low and high', $priority)); } } $prefix = Configure::read('Gearman.prefix'); if ($prefix) { $taskName = $prefix . '_' . $taskName; } $data = json_encode($data); CakeLog::debug(sprintf('Creating background job: %s', $taskName), array('gearman')); if ($priority == 'low') { $job = static::client()->doLowBackground($taskName, $data); } if ($priority == 'high') { $job = static::client()->doHighBackground($taskName, $data); } if (empty($priority)) { $job = static::client()->doBackground($taskName, $data); } if (static::client()->returnCode() !== GEARMAN_SUCCESS) { CakeLog::error(sprintf('Could not create background job for task %s and data %s. Got %s (%s)', $taskName, $data, $job, static::client()->error()), array('gearman')); return false; } return true; }
public static function execute($command, $cwd = null, $env = null, $allowSudo = true) { $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); \CakeLog::debug("Executing command: {$command}"); if (!empty($cwd)) { \CakeLog::debug("--> cwd = {$cwd}"); } // Execute command $process = proc_open($command, $descriptorspec, $pipes, $cwd, $env); if (!is_resource($process)) { \CakeLog::error("Could not execute command: {$command}"); throw new Exception("Could not execute command: {$command}"); } // close stdin fclose($pipes[0]); $stdout = $stderr = $buffer = $errbuf = ""; while (($buffer = fgets($pipes[1], 1024)) != NULL || ($errbuf = fgets($pipes[2], 1024)) != NULL) { if (!empty($buffer)) { $stdout .= $buffer; \CakeLog::debug('--> stdout: ' . trim($buffer)); } if (!empty($errbuf)) { $stderr .= $errbuf; \CakeLog::error('--> stderr: ' . trim($errbuf)); } } fclose($pipes[1]); fclose($pipes[2]); $exit_code = proc_close($process); \CakeLog::debug("--> exit_code: {$exit_code}"); unset($pipes[0], $pipes[1], $pipes[2], $pipes); unset($descriptorspec[0], $descriptorspec[1], $descriptorspec[2], $descriptorspec); return compact('stdout', 'stderr', 'exit_code', 'command', 'cwd', 'env'); }
/** * Load a list of $fixtures into a $source * * @param string $source The name of your datasource (e.g. default) * @param array $fixtures An array of fixtures - same format as in CakeTest $fixtures * @return void */ public function loadAllFixtures($source, $fixtures) { $this->_initDb($source); try { $this->_loadFixtures($fixtures); } catch (Exception $e) { CakeLog::error('-> ' . $e->getMessage(), array('fixturize')); } CakeLog::debug('Begin fixture import', array('fixturize')); $nested = $this->_db->useNestedTransactions; $this->_db->useNestedTransactions = false; $this->_db->begin(); foreach ($fixtures as $f) { CakeLog::debug(sprintf('Working on %s', $f)); if (empty($this->_loaded[$f])) { CakeLog::warning('-> Cannot find it in the loaded array', array('fixturize')); continue; } $fixture = $this->_loaded[$f]; CakeLog::debug(sprintf('-> Found fixture: %s', get_class($fixture)), array('fixturize')); $this->_setupTable($fixture, $this->_db, true); CakeLog::debug('-> Created table "OK"', array('fixture')); if ($fixture->insert($this->_db)) { CakeLog::debug('-> Inserted fixture data "OK"', array('fixturize')); } else { CakeLog::error('-> Inserted fixture data "ERROR"', array('fixturize')); } } $this->_db->commit(); $this->_useNestedTransactions = $nested; CakeLog::debug('Done!', array('fixturize')); }
public function parse(DOMElement $node) { $manager = IdmlDeclarationManager::getInstance(); foreach ($node->childNodes as $child) { if ($child->nodeType != XML_ELEMENT_NODE) { continue; } if ($child->nodeName == $this->groupTemplateName) { $classname = 'Idml' . $this->groupTemplateName; // something like 'IdmlParagraphStyleGroup' $obj = new $classname(); $name = $obj->parse($child); $manager->addDeclaredStyleGroup($name, $obj); $this->children[] = $name; } else { if ($child->nodeName == $this->styleTemplateName) { $classname = 'Idml' . $this->styleTemplateName; // something like 'IdmlParagraphStyle' $obj = new $classname(); $obj->parse($child); $name = $obj->idmlKeyValues['Self']; $manager->addDeclaredStyle($name, $obj); $this->children[] = $name; } else { CakeLog::debug("[IdmlDeclaredStyleGroup::parse] Unhandled tag <{$child->nodeName}>"); } } } return $node->hasAttribute('Self') ? $node->getAttribute('Self') : ''; }
/** * The getPositionCSS function should return a CSS declaration for the element's top and left. */ public function getPositionCSS(IdmlElement $element) { $elementClass = get_class($element); switch ($elementClass) { case 'IdmlTextFrame': case 'IdmlRectangle': case 'IdmlGroup': case 'IdmlPolygon': case 'IdmlOval': if (!isset($element->boundary)) { CakeLog::debug("[IdmlProduceFixedLayout::getDimensionCSS] Expecting boundary to provide position for " . get_class($element)); return ''; } if ($element->isEmbedded()) { // Get the positioning parameters, either from the inline styles or the applied style. // For now, store them in an array for easier passing to called methods. $positionParams['xOffset'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->AnchorXoffset', null); $positionParams['yOffset'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->AnchorYoffset', null); $positionParams['anchorPosition'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->AnchoredPosition', null); $positionParams['spineRelative'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->SpineRelative', null); $positionParams['anchorPoint'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->AnchorPoint', null); $positionParams['horizAlignment'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->HorizontalAlignment', null); $positionParams['horizRefPoint'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->HorizontalReferencePoint', null); $positionParams['vertAlignment'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->VerticalAlignment', null); $positionParams['vertRefPoint'] = $this->getStyleByKey($element, 'AnchoredObjectSetting->VerticalReferencePoint', null); // Only cases where 'AnchoredPosition' is 'Anchored' are offset if ($positionParams['anchorPosition'] != 'Anchored') { return 'position:relative;'; } // If no anchor offset is set, set position to relative and exit if (is_null($positionParams['xOffset']) && is_null($positionParams['yOffset'])) { return 'position:relative;'; } // At least one anchor offset is set, so set absolute positioning before determining final offsets $styles['position'] = 'absolute'; // Adjust offsets based on reference point list($xOffset, $yOffset) = $this->adjustOffsetsToRefPoint($positionParams, $element); if (!is_null($xOffset)) { $styles['left'] = $xOffset . 'px'; } // For now, we aren't managing 'top'. All test cases given use Baseline orientation, which is problematic in translation. // if (!is_null($yOffset)) // { // $styles['top'] = $yOffset . 'px'; // } $styleAttrib = $this->getStyleString($styles); return $styleAttrib; } else { $position = $this->getElementPosition($element); // Set element's position, to be used to relatively position embedded elements $element->setPosition($position); return sprintf("position:absolute; top:%spx; left:%spx;", $position['top'], $position['left']); } default: return ''; } }
public function request($endpoint, $action, $data = array()) { $this->socket = new HttpSocket(); $this->response = $this->socket->post("mpapi.localhost/{$endpoint}/{$action}.json", $data); CakeLog::debug(print_r($this->socket->request, true)); CakeLog::debug(print_r($this->response, true)); if ($this->response->isOk() && $this->response->body()) { return json_decode($this->response->body(), true); } else { return false; } }
/** * The parse function is the starting point for parsing the Styles.xml file. */ public function load($filename) { $manager = IdmlDeclarationManager::getInstance(); // Read the /Resources/Styles.xml file into a DOMDocument if (!file_exists($filename)) { CakeLog::debug("[IdmlDeclarationParser::load] Filename not found {$filename}"); return false; } $doc = new DOMDocument(); if ($doc->load($filename) === false) { CakeLog::debug("[IdmlDeclarationParser::load] Unable to read {$filename}"); return false; } $xpath = new DOMXPath($doc); // Recursively read each of the style groups and their hierarchy of styles $nodes = $xpath->query('//idPkg:Styles/RootCharacterStyleGroup'); if ($nodes->length > 0) { $obj = new IdmlCharacterStyleGroup(); $name = $obj->parse($nodes->item(0)); $manager->addDeclaredStyleGroup($name, $obj); } $nodes = $xpath->query('//idPkg:Styles/RootParagraphStyleGroup'); if ($nodes->length > 0) { $obj = new IdmlParagraphStyleGroup(); $name = $obj->parse($nodes->item(0)); $manager->addDeclaredStyleGroup($name, $obj); } $nodes = $xpath->query('//idPkg:Styles/RootObjectStyleGroup'); if ($nodes->length > 0) { $obj = new IdmlObjectStyleGroup(); $name = $obj->parse($nodes->item(0)); $manager->addDeclaredStyleGroup($name, $obj); } $nodes = $xpath->query('//idPkg:Styles/RootTableStyleGroup'); if ($nodes->length > 0) { $obj = new IdmlTableStyleGroup(); $name = $obj->parse($nodes->item(0)); $manager->addDeclaredStyleGroup($name, $obj); } $nodes = $xpath->query('//idPkg:Styles/RootCellStyleGroup'); if ($nodes->length > 0) { $obj = new IdmlCellStyleGroup(); $name = $obj->parse($nodes->item(0)); $manager->addDeclaredStyleGroup($name, $obj); } // Using each style's "BasedOn" property, flatten the hierarchy so that each style has all of it's parent's properties. $manager->resolveAll(); // Turn all properties which had duplicate names into an arrays foreach ($manager->declaredStyles as $styleName => $declaredStyle) { self::arrayifyDupes($styleName, $declaredStyle); } }
/** * Authenticates the identity contained in a request. Will use the `settings.userModel`, and `settings.fields` * to find POST data that is used to find a matching record in the `settings.userModel`. Will return false if * there is no post data, either username or password is missing, or if the scope conditions have not been met. * * @param CakeRequest $request The request that contains login information. * @param CakeResponse $response Unused response object. * @return mixed False on login failure. An array of User data on success. */ public function authenticate(CakeRequest $request, CakeResponse $response) { CakeLog::debug('ldap authenticate()'); $userModel = $this->settings['userModel']; list(, $model) = pluginSplit($userModel); $fields = $this->settings['fields']; if (!$this->_checkFields($request, $model, $fields)) { return false; } $con = ldap_connect('127.0.0.1'); $search = ldap_search($con, 'dc=netcommons,dc=local', 'cn=user1'); $result = ldap_get_entries($con, $search); CakeLog::debug('ldap search: ' . var_export($result, true)); return false; }
/** * Load image * * @param string $path Path to image relative to webroot * @param boolean $absolute Path is absolute server path * @return object $this */ public function source($path = '', $absolute = false) { $this->sizes = false; $this->serverPath = false; $this->_cacheServerPath = false; if (!$absolute) { $this->sourceDir = dirname($path); $path = ROOT . DS . APP_DIR . DS . 'Plugin' . DS . 'Paszport' . DS . WEBROOT_DIR . DS . $path; } CakeLog::debug($path); if ($this->sizes = @getimagesize($path)) { $this->serverPath = $path; } return $this; }
/** * Initialize the working directory and ensure it exists * @return string Path to working directory */ public function initWorkingDir() { // Check if working directory is already initialized if (is_dir($this->workingDir)) { return $this->workingDir; } // Get temp target directory $tmpDir = Configure::read('Chaucer.instanceName') . '/' . $this->bookId; $targetDir = Folder::addPathElement($this->FileManager->getTmpPath(), $tmpDir); // Create and return dir if (!$this->FileManager->createDir($targetDir)) { throw new Exception('Unable to create working directory: ' . $targetDir); } CakeLog::debug('[CommonProcessor::initWorkingDir] working dir: ' . $targetDir); return $targetDir; }
/** * タグ補完用検索 * * @return void */ public function search() { $keyword = $this->_getNamed('keyword', ''); $modelName = $this->_getNamed('target', ''); if (empty($keyword) || empty($modelName)) { return; } $blockId = Current::read('Block.id'); $conditions = array('name LIKE' => '%' . $keyword . '%', 'block_id' => $blockId, 'model' => $modelName); $tags = $this->Tag->find('all', array('conditions' => $conditions)); $results = array(); foreach ($tags as $tag) { $results[] = $tag['Tag']['name']; } CakeLog::debug(serialize($results)); $this->set('results', $results); $this->set('_serialize', ['results']); }
/** * Accept visitor. * * @param IdmlVisitor $visitor */ public function accept(IdmlVisitor $visitor, $depth = 0) { switch ($this->changeType) { case 'DeletedText': return; case 'InsertedText': case 'MovedText': $visitor->visitChange($this, $depth); foreach ($this->childrenElements as $child) { $child->accept($visitor, $depth + 1); } $visitor->visitChangeEnd($this, $depth); return; case 'undefined': default: CakeLog::debug("[IdmlChange::accept] Unexpected changeType '" . $this->changeType . "'"); return; } }
/** * The getPositionCSS function should return a CSS declaration for the element's top and left. * @param IdmlElement $element * @return string - containing style attributes (may be empty) */ public function getPositionCSS(IdmlElement $element) { $page = $this->getPage($element); if (is_null($page)) { throw new MissingComponentException('No page was found for ' . get_class($element) . '; UID ' . $element->UID); } $elementClass = get_class($element); switch ($elementClass) { case 'IdmlTextFrame': case 'IdmlRectangle': case 'IdmlGroup': case 'IdmlPolygon': case 'IdmlOval': case 'IdmlGraphicLine': if (!isset($element->boundary)) { CakeLog::debug("[IdmlProduceFixedLayout::getDimensionCSS] Expecting boundary to provide position for " . get_class($element)); return ''; } if ($element->isEmbedded()) { // Get the positioning parameters $positionParams = $this->getPositionParams($element, $page); $vertRefPoint = $positionParams['vertRefPoint']; // If there are values for IDML's AnchoredPosition property other than 'Anchored' and 'InlinePosition' we don't support them if ($positionParams['anchorPosition'] != 'Anchored' && $positionParams['anchorPosition'] != 'InlinePosition') { return 'position:relative;'; } // If no anchor offset is set, set position to relative and exit if (is_null($positionParams['xOffset']) && is_null($positionParams['yOffset'])) { return 'position:relative;'; } // Adjust offsets based on reference point $this->setRelativeOffsets($element, $positionParams, $page); list($left, $top) = $this->adjustOffsetsToRefPoint($element); } else { $vertRefPoint = null; list($left, $top) = $this->getElementPosition($element, $page); } return $this->getStyleString($element, $left, $top, $vertRefPoint); default: return ''; } }
/** * Stores multiple messages in the queue so it an external client can work upon them. * For performance reasons, it is better to create jobs in batches instead of one a time * if you plan to create several jobs in the same process or request. * * @param string $taskName a task name as defined in the configure key SQS.queues * @param array $payloads list of payload data to associate to the new queued message * for each entry in the array a new message in the queue will be created * @return array list of messages that failed to be sent or false if an exception was caught **/ public function sendBatch($taskName, array $payloads) { $url = $this->queueUrl($taskName); try { CakeLog::debug(sprintf('Creating %d messages in queue: %s', count($payloads), $taskName), array('sqs')); $result = $this->client()->sendMessageBatch(array('QueueUrl' => $url, 'Entries' => array_map(function ($e) use(&$i) { return array('Id' => 'a' . $i++, 'MessageBody' => json_encode($e)); }, $payloads))); $failed = array(); foreach ((array) $result->get('Failed') as $f) { $failed[(int) substr($f['Id'], 1)] = $f['Message']; } if (!empty($failed)) { CakeLog::warning(sprintf('Failed sending %d messages for queue: %s', count($failed), $taskName), array('sqs')); } return $failed; } catch (Exception $e) { $this->_handleException($e); } return false; }
public function parse(DOMElement $node) { parent::parse($node); //parse and set row attributes that are based upon parent table $rownum = $node->hasAttribute('Name') ? intval($node->getAttribute('Name')) : 0; $table = $this->parentIdmlObject(); if (IdmlParserHelper::getIdmlObjectType($table) == "Table") { //set this row in the table rows array by index $table->rows[$rownum] = $this; //from Indesign the order of rows is header, body, footer //we must set what type of row this is and whether it is first and/or last in its group if ($table->headerRowCount && $rownum < $table->headerRowCount) { $this->rowType = 'thead'; $rowGroupStart = 0; $rowGroupEnd = $table->headerRowCount - 1; } elseif ($table->bodyRowCount && $rownum < $table->headerRowCount + $table->bodyRowCount) { $this->rowType = 'tbody'; $rowGroupStart = $table->headerRowCount; $rowGroupEnd = $table->headerRowCount + $table->bodyRowCount - 1; } elseif ($table->footerRowCount && $rownum < $table->headerRowCount + $table->bodyRowCount + $table->footerRowCount) { $this->rowType = 'tfoot'; $rowGroupStart = $table->headerRowCount + $table->bodyRowCount; $rowGroupEnd = $table->headerRowCount + $table->bodyRowCount + $table->footerRowCount - 1; } else { //this is a problem as we can't place the row? CakeLog::debug("[IdmlTableRow::parse] unable to identify tablerow type and place in group " . __FILE__ . " Line " . __LINE__); } if ($rownum == $rowGroupStart) { $this->isFirstRow = true; } if ($rownum == $rowGroupEnd) { $this->isLastRow = true; } } else { //something is wrong so log this? CakeLog::debug("[IdmlTableRow::parse] parent is not an IdmlTable?" . __FILE__ . " Line " . __LINE__); } //TableRow has no children to parse }
/** * close * * zipの作成 * * @return bool */ public function close() { // zip作成先 $zipSaveFolder = new TemporaryFolder(); $this->path = $zipSaveFolder->path . DS . Security::hash(mt_rand() . microtime(), 'md5') . '.zip'; if (strlen($this->_password)) { // パスワードを使う $cmd = $this->_zipCommand; $execCmd = sprintf('%s -r -e -P %s %s %s', $cmd, escapeshellarg($this->_password), escapeshellarg($this->path), '*'); chdir($this->_tmpFolder->path); // コマンドを実行する //exec(($execCmd)); exec($execCmd, $output, $returnVar); //CakeLog::debug($execCmd); if ($returnVar > 0) { CakeLog::debug(' Error:output=' . json_encode($output) . ', return_var=' . $returnVar); return false; } } else { // パスワード無しZIP // ZipArchiverを使う $zip = new ZipArchive(); $zip->open($this->path, ZipArchive::CREATE); chdir($this->_tmpFolder->path); list($folders, $files) = $this->_tmpFolder->tree(); foreach ($folders as $folder) { if ($folder !== $this->_tmpFolder->path) { $relativePath = str_replace($this->_tmpFolder->path . DS, '', $folder); $zip->addEmptyDir($this->_convertFilename($relativePath)); } } foreach ($files as $file) { $relativePath = str_replace($this->_tmpFolder->path . DS, '', $file); $zip->addFile($relativePath, $this->_convertFilename($relativePath)); } $zip->close(); } $this->_open = false; }
public function convert() { // TextWrapMode possible values: // None, JumpObjectTextWrap, NextColumnTextWrap, BoundingBoxTextWrap, Contour $textWrapMode = $this->getAppliedStyleKeyValue('TextWrapPreference->TextWrapMode', 'None'); if ($textWrapMode == 'None') { return; } // TextWrapSide possible values: // BothSides, LeftSide, RightSide, SideTowardsSpine, SideAwayFromSpine, LargestArea $textWrapSide = $this->getAppliedStyleKeyValue('TextWrapPreference->TextWrapSide', 'LeftSide'); switch ($textWrapSide) { case 'LeftSide': $this->registerCSS('float', 'right'); break; case 'BothSides': case 'RightSide': $this->registerCSS('float', 'left'); break; case 'SideTowardsSpine': case 'SideAwayFromSpine': default: CakeLog::debug("[IdmlDecodeTextWrap:convert] unhandled TextWrapSide={$textWrapSide}"); return; } $offsetTop = $this->getAppliedStyleKeyValue('TextWrapPreference::Properties::TextWrapOffset->Top', '0'); $offsetLeft = $this->getAppliedStyleKeyValue('TextWrapPreference::Properties::TextWrapOffset->Left', '0'); $offsetBottom = $this->getAppliedStyleKeyValue('TextWrapPreference::Properties::TextWrapOffset->Bottom', '0'); $offsetRight = $this->getAppliedStyleKeyValue('TextWrapPreference::Properties::TextWrapOffset->Right', '0'); if ($offsetTop == $offsetLeft && $offsetLeft == $offsetBottom && $offsetBottom == $offsetRight) { $this->registerCSS('margin', $offsetTop . 'px'); } else { $this->registerCSS('margin-top', $offsetTop . 'px'); $this->registerCSS('margin-left', $offsetLeft . 'px'); $this->registerCSS('margin-bottom', $offsetBottom . 'px'); $this->registerCSS('margin-right', $offsetRight . 'px'); } }
public function parse(DOMElement $node) { parent::parse($node); //we must set the <col style='width:...' /> for this column in the table $this->rowspan = $node->hasAttribute('RowSpan') ? intval($node->getAttribute('RowSpan')) : -1; $this->colspan = $node->hasAttribute('ColumnSpan') ? intval($node->getAttribute('ColumnSpan')) : -1; // Right now the parent is a table element, but we need the parent to be the corresponding row for this cell. // Find the right row in the table array and assign it as this cell's parent ImdlElement. $colrow = $node->hasAttribute('Name') ? $node->getAttribute('Name') : '0:0'; $colrowArray = explode(":", $colrow); // <col>:<row> $this->colnumber = intval($colrowArray[0]); $this->rownumber = intval($colrowArray[1]); $row = $this->parentElement->rows[$this->rownumber]; if (IdmlParserHelper::getIdmlObjectType($row) == "TableRow") { /*@var $row IdmlTableRow*/ $row->childrenElements[] = $this; $this->parentElement = $row; //assign this cell as child of the table row } else { CakeLog::debug("[IdmlTableCell::parse] cannot find parent row in table for cell? " . __FILE__ . " Line " . __LINE__); } $this->parseChildren($node); }
/** * 投稿メール - メールキューSave * 公開時を想定 * * @param Model $model モデル * @param int $languageId 言語ID * @param array $sendTimes メール送信日時 配列 * @param array $userIds 送信ユーザID 配列 * @param array $toAddresses 送信先メールアドレス 配列 * @param int $roomId ルームID * @param string $typeKey メールの種類 * @return void * @throws InternalErrorException */ public function saveQueuePostMail(Model $model, $languageId, $sendTimes = null, $userIds = null, $toAddresses = null, $roomId = null, $typeKey = MailSettingFixedPhrase::DEFAULT_TYPE) { $model->Behaviors->load('Mails.IsMailSend', $this->settings[$model->alias]); if ($sendTimes === null) { $sendTimes[] = $model->MailQueue->getSaveSendTime(); } // 末尾定型文 なし $mailQueue = $this->__createMailQueue($model, $languageId, $typeKey); // 末尾定型文 あり $fixedPhraseBodyAfter = $this->settings[$model->alias][self::MAIL_QUEUE_SETTING_MAIL_BODY_AFTER]; $mailQueueBodyAfter = $this->__createMailQueue($model, $languageId, $typeKey, null, $fixedPhraseBodyAfter); $contentKey = $this->__getContentKey($model); $pluginKey = $this->settings[$model->alias]['pluginKey']; $blockKey = Current::read('Block.key'); // MailQueueUser $mailQueueUser['MailQueueUser'] = array('plugin_key' => $pluginKey, 'block_key' => $blockKey, 'content_key' => $contentKey, 'user_id' => null, 'room_id' => null, 'to_address' => null, 'send_room_permission' => null, 'not_send_room_user_ids' => null); // 以下、実行する時は、公開時を想定 foreach ($sendTimes as $sendTime) { /** @see IsMailSendBehavior::isMailSendTime() */ // cron使えず未来日メールなら、送らない if (!$model->isMailSendTime($sendTime)) { CakeLog::debug('[' . __METHOD__ . '] ' . __FILE__ . ' (line ' . __LINE__ . ')'); return; } $sendTime = $model->MailQueue->getSaveSendTime($sendTime); if (!empty($userIds)) { // メール内容save $mailQueueUser['MailQueueUser']['mail_queue_id'] = $this->__saveMailQueue($model, $mailQueue, $sendTime); // --- ユーザIDに配信 /** @see MailQueueUser::addMailQueueUsers() */ $model->MailQueueUser->addMailQueueUsers($mailQueueUser, 'user_id', $userIds); } if (!empty($toAddresses)) { // メール内容save $mailQueueUser['MailQueueUser']['mail_queue_id'] = $this->__saveMailQueue($model, $mailQueue, $sendTime); // --- メールアドレスに配信 /** @see MailQueueUser::addMailQueueUsers() */ $model->MailQueueUser->addMailQueueUsers($mailQueueUser, 'to_address', $toAddresses); } if (!empty($roomId)) { // メール内容save - 末尾定型文あり $mailQueueUser['MailQueueUser']['mail_queue_id'] = $this->__saveMailQueue($model, $mailQueueBodyAfter, $sendTime); // --- ルーム配信 // ルーム配信で送らないユーザID $key = self::MAIL_QUEUE_SETTING_NOT_SEND_ROOM_USER_IDS; $notSendRoomUserIds = $this->settings[$model->alias][$key]; $notSendRoomUserIds = Hash::merge($notSendRoomUserIds, $userIds); $this->settings[$model->alias][$key] = $notSendRoomUserIds; // 登録者に配信 $this->__addMailQueueUserInCreatedUser($model, $mailQueueUser['MailQueueUser']['mail_queue_id']); // 登録者に配信で、ルーム配信で送らないユーザIDをセットしているので、再取得 $notSendRoomUserIds = $this->settings[$model->alias][$key]; // ルーム配信で送るパーミッション /** @see MailQueueUser::getSendRoomPermission() */ $sendRoomPermission = $model->MailQueueUser->getSendRoomPermission($typeKey); // ルーム配信 /** @see MailQueueUser::addMailQueueUserInRoom() */ $model->MailQueueUser->addMailQueueUserInRoom($roomId, $mailQueueUser, $sendTime, $notSendRoomUserIds, $sendRoomPermission); } } }
/** * test convenience methods * * @return void */ public function testConvenienceMethods() { $this->_deleteLogs(); CakeLog::config('debug', array('engine' => 'File', 'types' => array('notice', 'info', 'debug'), 'file' => 'debug')); CakeLog::config('error', array('engine' => 'File', 'types' => array('emergency', 'alert', 'critical', 'error', 'warning'), 'file' => 'error')); $testMessage = 'emergency message'; CakeLog::emergency($testMessage); $contents = file_get_contents(LOGS . 'error.log'); $this->assertRegExp('/(Emergency|Critical): ' . $testMessage . '/', $contents); $this->assertFalse(file_exists(LOGS . 'debug.log')); $this->_deleteLogs(); $testMessage = 'alert message'; CakeLog::alert($testMessage); $contents = file_get_contents(LOGS . 'error.log'); $this->assertRegExp('/(Alert|Critical): ' . $testMessage . '/', $contents); $this->assertFalse(file_exists(LOGS . 'debug.log')); $this->_deleteLogs(); $testMessage = 'critical message'; CakeLog::critical($testMessage); $contents = file_get_contents(LOGS . 'error.log'); $this->assertContains('Critical: ' . $testMessage, $contents); $this->assertFalse(file_exists(LOGS . 'debug.log')); $this->_deleteLogs(); $testMessage = 'error message'; CakeLog::error($testMessage); $contents = file_get_contents(LOGS . 'error.log'); $this->assertContains('Error: ' . $testMessage, $contents); $this->assertFalse(file_exists(LOGS . 'debug.log')); $this->_deleteLogs(); $testMessage = 'warning message'; CakeLog::warning($testMessage); $contents = file_get_contents(LOGS . 'error.log'); $this->assertContains('Warning: ' . $testMessage, $contents); $this->assertFalse(file_exists(LOGS . 'debug.log')); $this->_deleteLogs(); $testMessage = 'notice message'; CakeLog::notice($testMessage); $contents = file_get_contents(LOGS . 'debug.log'); $this->assertRegExp('/(Notice|Debug): ' . $testMessage . '/', $contents); $this->assertFalse(file_exists(LOGS . 'error.log')); $this->_deleteLogs(); $testMessage = 'info message'; CakeLog::info($testMessage); $contents = file_get_contents(LOGS . 'debug.log'); $this->assertRegExp('/(Info|Debug): ' . $testMessage . '/', $contents); $this->assertFalse(file_exists(LOGS . 'error.log')); $this->_deleteLogs(); $testMessage = 'debug message'; CakeLog::debug($testMessage); $contents = file_get_contents(LOGS . 'debug.log'); $this->assertContains('Debug: ' . $testMessage, $contents); $this->assertFalse(file_exists(LOGS . 'error.log')); $this->_deleteLogs(); }
/** * Parse from DOM node. * @param DOMElement $node */ public function parse(DOMElement $node) { parent::parse($node); // $this->styleInfo['inlineStyle']->translateSingleColumnWidth(); //set Css width for column /* if($this->hasIdmlProperty('SingleColumnWidth')) { $val = $this->getIdmlProperty('SingleColumnWidth'); if(is_numeric($val)) { $val = round($val); $this->addCssProperty('width', $val . 'pt'); } } */ /* //add needed column info to parent table because IdmlHtmlProducer needs this at the IdmlTable element level if($this->styleInfo["inlineStyle"]->hasCssProperty('width')) { $table = $this->parentIdmlObject(); if(IdmlParserHelper::getIdmlObjectType($table) == "Table") { $table->cols[] = $this; $colwidth = $this->styleInfo["inlineStyle"]->getCssPropertyString('width'); if($colwidth) { $table->colGroupStyles[] = $colwidth; } } } else { CakeLog::debug("[IdmlTableColumn::parse] column width not found? ".__FILE__." Line ".__LINE__); } */ if ($node->hasAttribute('SingleColumnWidth')) { $singleColumnWidth = round($node->getAttribute('SingleColumnWidth')); $table = $this->parentIdmlObject(); if (IdmlParserHelper::getIdmlObjectType($table) == "Table") { $table->cols[] = $this; $colwidth = 'width:' . $singleColumnWidth . 'pt;'; $table->colGroupStyles[] = $colwidth; } } else { CakeLog::debug("[IdmlTableColumn::parse] column width not found? " . __FILE__ . " Line " . __LINE__); } //IdmlTableColumn has no children to parse }
/** * Parse the portion of a spread.xml file that contains a <TextFrame> * * @param DOMElement $node is a single <TextFrame> node within the IDML document */ public function parse(DOMElement $node) { parent::parse($node); $attributes = $node->attributes; $this->UID = $attributes->getNamedItem('Self')->value; // like 'uf9' $this->parentStoryUID = $attributes->getNamedItem('ParentStory')->value; // like 'ue5' $this->contentType = $attributes->getNamedItem('ContentType')->value; // like 'TextType' $this->visible = $attributes->getNamedItem('Visible')->value == 'false' ? false : true; // like 'true' $this->setTransform($node); $this->boundary = IdmlParserHelper::parseBoundary($node); $this->prevTextFrame = $attributes->getNamedItem(IdmlAttributes::PreviousTextFrame)->value == 'n' ? null : $attributes->getNamedItem(IdmlAttributes::PreviousTextFrame)->value; $this->nextTextFrame = $attributes->getNamedItem(IdmlAttributes::NextTextFrame)->value == 'n' ? null : $attributes->getNamedItem(IdmlAttributes::NextTextFrame)->value; $this->textColumnCount = isset($this->contextualStyle->idmlKeyValues['TextFramePreference->TextColumnCount']) ? (int) $this->contextualStyle->idmlKeyValues['TextFramePreference->TextColumnCount'] : null; $this->columnWidth = isset($this->contextualStyle->idmlKeyValues['TextFramePreference->TextColumnFixedWidth']) ? $this->contextualStyle->idmlKeyValues['TextFramePreference->TextColumnFixedWidth'] : null; // If we *do_not_have* a previous text frame then it is either a single text frame or the first of a series of // linked ones. In case of linked ones we output only the first one. if (!$this->prevTextFrame) { $this->loadParentStory(); } else { if (IdmlAssembler::getInstance()->isFixedLayout()) { CakeLog::debug("[IdmlTextFrame::parse] Encountered an InDesign threaded frame in a fixed layout book (story {$this->parentStoryUID}). Run Chaucer FixedLayoutPreflight.jsx script within InDesign and re-export the IDML."); } } }
/** The lookupStory function is called by IdmlSpread when it encounters a <TextFrame> in a <idPkg:Spread>. * Use this function to find the IdmlStory that has the given $UID. * * @param string $UID is the InDesign unique identifier given to the story, like 'ue5' * * @return IdmlStory|null Returns the IdmlStory with the given $UID. * This function typically will not return null and those cases should be treated as runtime errors. */ public function lookupStory($UID) { if (array_key_exists($UID, $this->stories)) { $idmlStory = $this->stories[$UID]; return $idmlStory; } else { CakeLog::debug("[IdmlPackage::lookupStory] Unable to find story '{$UID}'"); return null; } }
/** * Process Payments * @param string $referenceId * @param array $paymentMethods * @param bool $test_mode * @return array */ public function processOrderPayments($referenceId, $paymentMethods, $test_mode = false) { syslog(LOG_DEBUG, "Order Payments {$referenceId} " . count($paymentMethods)); $creditCards = []; $oxxoPayments = []; $giroPayments = []; $sofortPayments = []; $paypalPayments = []; $ledgerMethods = []; foreach ($paymentMethods as $payment) { switch ($payment['type']) { case OrderPayment::TYPE_LEDGER_NAME: $ledgerMethods[] = $payment; break; case OrderPayment::TYPE_CREDITCARD_NAME: $creditCards[] = $payment; break; case OrderPayment::TYPE_PAYPAL_NAME: $paypalPayments[] = $payment; break; case OrderPayment::TYPE_OXXO_NAME: $oxxoPayments[] = $payment; break; case OrderPayment::TYPE_GIRO_NAME: $giroPayments[] = $payment; break; case OrderPayment::TYPE_SOFORT_NAME: $sofortPayments[] = $payment; break; } } $processedPayments = []; try { if (count($ledgerMethods) > 0) { $this->ProductCredit = ClassRegistry::init('ProductCredit'); foreach ($ledgerMethods as $payment) { $result = $this->ProductCredit->authorize(ProductCredit::METHOD_SYSTEM, ProductCredit::TYPE_PURCHASE, Configure::read("market_id"), $payment['presenter_id'], $payment['user_id'], $payment['amount'], "System", $referenceId); $payment['identifier'] = $payment['user_id']; if ($result !== false) { $payment['transaction_id'] = $result; $payment['status'] = "authorized"; $processedPayments[] = $payment; } else { $payment['status'] = "failed"; $payment['transaction_id'] = "0"; return $this->voidTransactions($processedPayments, "Insufficient Product Credits"); } } } if (count($giroPayments) > 0) { foreach ($giroPayments as $payment) { $mid = Configure::read('market_id'); $agent = $_SERVER['HTTP_USER_AGENT']; // unset($payment['processor']); // unset($payment['type']); try { $p = $payment; $p['amount'] = $payment['amount']->amount; $result = $this->WorldPayGiro->purchase($mid, $p, $agent, $test_mode); } catch (WorldPayError $e) { if ($e->getMessage() == WorldPay::$RESPONSE_ERROR) { if ($this->WorldPayGiro->api->reply->hasError()) { $response = $this->WorldPayGiro->api->reply; $result = ['success' => false, 'error' => ['errno' => $response->err_code, 'errmsg' => $response->err_msgs]]; } else { $result = ['success' => false, 'error' => ['errno' => '500', 'errmsg' => 'Server Error']]; } } else { $result = ['success' => false, 'error' => ['errno' => '401', 'errmsg' => 'Authentication Failed']]; } } if (!$result['success']) { $payment['status'] = 'failed'; $error = " Code: " . $result['error']['errno'] . " Message: " . $result['error']['errmsg']; if (!empty($result['error']['errno'])) { // log to api log table $this->ApiAudit = ClassRegistry::init('ApiAudit'); $api_data = ['reference_name' => get_class(), 'reference_id' => 0, 'source' => __FILE__ . ' ' . __LINE__, 'destination' => 'worldpay api', 'sent' => json_encode($payment), 'received' => $error, 'notes' => 'World Pay Giro fail']; $this->ApiAudit->clear(); $this->ApiAudit->create($api_data); $this->ApiAudit->save(); } $error = __('There was a payment error. Please contact support.'); return $this->voidTransactions($processedPayments, $error); } else { // For giro save reference and redirect $payment['status'] = "success"; $payment['redirect'] = true; $payment['identifier'] = 0; $payment['processor'] = PaymentComponent::GATEWAY_WORLDPAY_GIRO; $payment['transaction_id'] = $result['reply']->response->reply->orderStatus->reference; $processedPayments[] = $payment; } } } if (count($sofortPayments) > 0) { foreach ($sofortPayments as $payment) { $mid = Configure::read('market_id'); $agent = $_SERVER['HTTP_USER_AGENT']; // unset($payment['processor']); // unset($payment['type']); try { $p = $payment; $p['amount'] = $payment['amount']->amount; $result = $this->WorldPaySofort->purchase($mid, $p, $agent, $test_mode); } catch (WorldPayError $e) { if ($e->getMessage() == WorldPay::$RESPONSE_ERROR) { if ($this->WorldPaySofort->api->reply->hasError()) { $response = $this->WorldPaySofort->api->reply; $result = ['success' => false, 'error' => ['errno' => $response->err_code, 'errmsg' => $response->err_msgs]]; } else { $result = ['success' => false, 'error' => ['errno' => '500', 'errmsg' => 'Server Error']]; } } else { $result = ['success' => false, 'error' => ['errno' => '401', 'errmsg' => 'Authentication Failed']]; } } if (!$result['success']) { $payment['status'] = 'failed'; $error = " Code: " . $result['error']['errno'] . " Message: " . $result['error']['errmsg']; if (!empty($result['error']['errno'])) { // log to api log table $this->ApiAudit = ClassRegistry::init('ApiAudit'); $api_data = ['reference_name' => get_class(), 'reference_id' => 0, 'source' => __FILE__ . ' ' . __LINE__, 'destination' => 'worldpay api', 'sent' => json_encode($payment), 'received' => $error, 'notes' => 'World Pay Sofort fail']; $this->ApiAudit->clear(); $this->ApiAudit->create($api_data); $this->ApiAudit->save(); } $error = __('There was a payment error. Please contact support.'); return $this->voidTransactions($processedPayments, $error); } else { // For sofort save reference and redirect $payment['status'] = "success"; $payment['redirect'] = true; $payment['identifier'] = 0; $payment['processor'] = PaymentComponent::GATEWAY_WORLDPAY_SOFORT; $payment['transaction_id'] = $result['reply']->response->reply->orderStatus->reference; $processedPayments[] = $payment; } } } if (count($oxxoPayments) > 0) { foreach ($oxxoPayments as $payment) { $mid = Configure::read('market_id'); $agent = $_SERVER['HTTP_USER_AGENT']; // unset($payment['processor']); // unset($payment['type']); try { $p = $payment; $p['amount'] = $payment['amount']->amount; $result = $this->WorldPayOxxo->purchase($mid, $p, $agent, $test_mode); } catch (WorldPayError $e) { if ($e->getMessage() == WorldPay::$RESPONSE_ERROR) { if ($this->WorldPayOxxo->api->reply->hasError()) { $response = $this->WorldPayOxxo->api->reply; $result = ['success' => false, 'error' => ['errno' => $response->err_code, 'errmsg' => $response->err_msgs]]; } else { $result = ['success' => false, 'error' => ['errno' => '500', 'errmsg' => 'Server Error']]; } } else { $result = ['success' => false, 'error' => ['errno' => '401', 'errmsg' => 'Authentication Failed']]; } } if (!$result['success']) { $payment['status'] = 'failed'; $error = " Code: " . $result['error']['errno'] . " Message: " . $result['error']['errmsg']; if (!empty($result['error']['errno'])) { // log to api log table $this->ApiAudit = ClassRegistry::init('ApiAudit'); $api_data = ['reference_name' => get_class(), 'reference_id' => 0, 'source' => __FILE__ . ' ' . __LINE__, 'destination' => 'worldpay api', 'sent' => json_encode($payment), 'received' => $error, 'notes' => 'World Pay fail']; $this->ApiAudit->clear(); $this->ApiAudit->create($api_data); $this->ApiAudit->save(); } $error = __('There was a payment error. Please contact support.'); return $this->voidTransactions($processedPayments, $error); } else { // For oxxo save reference and redirect $payment['status'] = "success"; $payment['redirect'] = true; $payment['identifier'] = 0; $payment['processor'] = PaymentComponent::GATEWAY_WORLDPAY_OXXO; $payment['transaction_id'] = $result['reply']->response->reply->orderStatus->reference; $processedPayments[] = $payment; } } } if (count($creditCards) > 0) { foreach ($creditCards as $payment) { $payment['identifier'] = substr($payment['cardnum'], -4); switch ($payment['processor']) { case self::GATEWAY_WORLDPAY: $currency = $this->WorldPay->getCurrency(Configure::read("market_id")); $mid = Configure::read('market_id'); $agent = $_SERVER['HTTP_USER_AGENT']; $data = ['amount' => $payment['amount']->amount, 'currency' => $currency, 'ip_address' => $payment['ip_address'], 'email' => $payment['email'], 'session_id' => $payment['session_id'], 'id' => $payment['orderId'], 'address' => $payment['billing'], 'card' => ['accountNumber' => $payment['cardnum'], 'expirationMonth' => $payment['cardExpMonth'], 'expirationYear' => $payment['cardExpYear'], 'cvv' => $payment['cardcode'], 'firstName' => $payment['firstName'], 'lastName' => $payment['lastName']]]; try { $result = $this->WorldPay->purchase($mid, $data, $agent, $test_mode); } catch (WorldPayError $e) { if ($e->getMessage() == WorldPay::$RESPONSE_ERROR) { if ($this->WorldPay->api->reply->hasError()) { $response = $this->WorldPay->api->reply; $result = ['success' => false, 'error' => ['errno' => $response->err_code, 'errmsg' => $response->err_msgs]]; } else { $result = ['success' => false, 'error' => ['errno' => '500', 'errmsg' => 'Server Error']]; } } else { $result = ['success' => false, 'error' => ['errno' => '401', 'errmsg' => 'Authentication Failed']]; } } if (!$result['success']) { $payment['status'] = 'failed'; $error = " Code: " . $result['error']['errno'] . " Message: " . $result['error']['errmsg']; if (!empty($result['error']['errno'])) { // log to api log table $this->ApiAudit = ClassRegistry::init('ApiAudit'); unset($data['card']); $api_data = ['reference_name' => get_class(), 'reference_id' => 0, 'source' => __FILE__ . ' ' . __LINE__, 'destination' => 'worldpay api', 'sent' => json_encode($data), 'received' => $error, 'notes' => 'World Pay fail']; $this->ApiAudit->clear(); $this->ApiAudit->create($api_data); $this->ApiAudit->save(); } $error = __('There was a payment error. Please contact support.'); return $this->voidTransactions($processedPayments, $error); } else { $payment['status'] = "success"; $card_num = substr($result['reply']->response->reply->orderStatus->payment->cardNumber, -4); $payment['identifier'] = $card_num; $payment['transaction_id'] = $result['reply']->response->reply->orderStatus['orderCode']; //World Pay : Credit Cards Only if (substr($result['reply']->response->reply->orderStatus->payment->cardNumber, 0, 1) == '4') { //All Visa cards start with 4 $payment['paid_with'] = 'visa'; } elseif (in_array(substr($result['reply']->response->reply->orderStatus->payment->cardNumber, 0, 2), ['51', '52', '53', '54', '55'])) { //All MasterCard cards start with either 51,52,53,54,55 $payment['paid_with'] = 'mastercard'; } $processedPayments[] = $payment; } break; case self::GATEWAY_PAYPAL: $result = $this->Paypal->process($referenceId, (string) $payment['amount'], $payment['firstName'], $payment['lastName'], $payment['billingpostalcode'], $payment['cardnum'], $payment['carexp'], $payment['cardcode']); if ($result->Ack != "Success") { $payment['status'] = "failed"; $payment['transaction_id'] = $result->TransactionID; return $this->voidTransactions($processedPayments, $result->Errors->LongMessage); } else { $payment['transaction_id'] = $result->TransactionID; $payment['status'] = "success"; $processedPayments[] = $payment; } break; case self::GATEWAY_CYBERSOURCE: $ip = array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; try { if (strlen($payment['billingpostalcode']) > 10) { throw new Exception("billing postal code not valid."); } } catch (Exception $e) { return false; } $billTo = array("email" => $payment['billingemail'], "city" => $payment['billingcity'], "firstName" => $payment['firstName'], "lastName" => $payment['lastName'], "postalCode" => $payment['billingpostalcode'], "state" => $payment['billingstate'], "street1" => $payment['billingaddress1'], "street2" => $payment['billingaddress2'], "country" => $payment['billingcountry'], "ipAddress" => $ip); //format exp for cybersource $exp_month = substr($payment['carexp'], 0, 2); $exp_year = substr($payment['carexp'], 3, 4); $card = array("accountNumber" => $payment['cardnum'], "expirationMonth" => $exp_month, "expirationYear" => $exp_year, "cvv" => $payment['cardcode']); $purchaseTotals = array("grandTotalAmount" => (string) $payment['amount']); $result = $this->Cybersource->purchase($billTo, $card, $purchaseTotals); $payment['transaction_id'] = $result->requestID; $payment['processor'] = OrderPaymentProcessor::PROCESSOR_CYBERSOURCE; if ($result->reasonCode != 100) { $payment['status'] = "failed"; return $this->voidTransactions($processedPayments, $this->Cybersource->reasonDescriptions[$result->reasonCode]); } else { $payment['status'] = "success"; $processedPayments[] = $payment; } break; case self::GATEWAY_BRAINTREE: $result = $this->Braintree->purchase($payment, $_POST['device_data']); if (YOUNIQUE_TESTSERVER) { CakeLog::debug(var_export($result, true)); } if ($result->success) { $payment['status'] = "success"; $payment['paid_with'] = ''; if (!empty($result->transaction->creditCardDetails->last4)) { $payment['identifier'] = $result->transaction->creditCardDetails->last4; if (substr($result->transaction->creditCardDetails->maskedNumber, 0, 1) == '4') { //All Visa cards start with 4 $payment['paid_with'] = 'visa'; } elseif (in_array(substr($result->transaction->creditCardDetails->maskedNumber, 0, 2), ['51', '52', '53', '54', '55'])) { //All MasterCard cards start with either 51,52,53,54,55 $payment['paid_with'] = 'mastercard'; } } else { if (!empty($result->transaction->paypalDetails->paymentId)) { $payment['identifier'] = $result->transaction->paypalDetails->payerEmail; $payment['paid_with'] = 'paypal'; } else { $payment['identifier'] = $result->transaction->id; } } $payment['transaction_id'] = $result->transaction->id; $processedPayments[] = $payment; } else { if (isset($result->errors)) { $errors = $result->errors->deepAll(); } if (!empty($errors)) { // errors can be referenced here: // https://developers.braintreepayments.com/javascript+php/sdk/server/transaction-processing/validations $api_errors = $result->errors->deepAll(); $errors = []; foreach ($api_errors as $key => $value) { $errors[] = $value->message; } $internal_use_error = implode(" ", $errors); $error = __('There was an error. Please contact support.'); // log to api log table $this->ApiAudit = ClassRegistry::init('ApiAudit'); $api_data = ['reference_name' => get_class(), 'reference_id' => 0, 'source' => __FILE__ . ' ' . __LINE__, 'destination' => 'braintree api', 'sent' => json_encode($this->Braintree->payment_data), 'received' => $internal_use_error, 'notes' => 'Braintree validation fail']; $this->ApiAudit->clear(); $this->ApiAudit->create($api_data); $this->ApiAudit->save(); } else { // decline /** * Error overwrites as per Michael Gulbrandsen */ switch ($result->transaction->processorResponseCode) { case 1000: $error = "We are unable to process your transaction given the " . "information provided. Please provide an alternate form of " . "payment or reach out to your bank for more information."; break; case 3000: $error = "We're sorry, we cannot process your transaction " . "at this time. Please try again."; break; default: $subject = "BrainTree Payment Decline"; $error = "We are unable to process your transaction given the " . "information provided. Please provide an alternate form of " . "payment or reach out to your bank for more information."; $message = "Status: " . $result->transaction->status . " Code: " . $result->transaction->processorResponseCode . " Message: " . $result->transaction->processorResponseText . "\n"; $message .= var_export($result, true); SNS::sendSNS("Payment_Declines", $subject, $message); break; } } return $this->voidTransactions($processedPayments, $error); } break; default: return FALSE; break; } } } if (count($paypalPayments) > 0) { foreach ($paypalPayments as $payment) { $expressPayment = $this->Paypal->getExpressCheckout($payment['token']); //need to return token, paypal user id, amount, and currency $token = $expressPayment->GetExpressCheckoutDetailsResponseDetails->Token; $payerId = $expressPayment->GetExpressCheckoutDetailsResponseDetails->PayerInfo->PayerID; $amount = $expressPayment->GetExpressCheckoutDetailsResponseDetails->PaymentDetails->OrderTotal->value; $currency = $expressPayment->GetExpressCheckoutDetailsResponseDetails->PaymentDetails->OrderTotal->currencyID; //can compare payer userid, amount, currency to validate transaction here if needed //also could make sure the receiving acct is correct $result = $this->Paypal->doExpressCheckout($token, $payerId, $amount, $currency); $payment['identifier'] = $payment['user_id']; if ($result->Ack != "Success") { $payment['status'] = "failed"; if (isset($result->TransactionID)) { $payment['transaction_id'] = $result->TransactionID; } return $this->voidTransactions($processedPayments, $result->Errors->LongMessage); } else { $payment['transaction_id'] = $result->DoExpressCheckoutPaymentResponseDetails->PaymentInfo->TransactionID; $payment['status'] = "success"; $processedPayments[] = $payment; } } } foreach ($processedPayments as $key => $payment) { if ($processedPayments[$key]['type'] == OrderPayment::TYPE_LEDGER_NAME) { $this->ProductCredit->capture($processedPayments[$key]['presenter_id'], $processedPayments[$key]['user_id'], $processedPayments[$key]['transaction_id']); $processedPayments[$key]['status'] = "success"; } } } catch (Exception $e) { if (YOUNIQUE_TESTSERVER != true) { YouniqueEmail::queueEmail(['date' => date('Y-m-d H:i:s'), 'reference_id' => $referenceId, 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString()], 'admin/paymentfailure', '*****@*****.**', 'Payment failure', 'paymentFailure', 'en_US'); } return ["success" => false]; } return ["success" => true, "payments" => $processedPayments]; }
/** * ブロック状態によってメール送る、送らないチェック * (ブロック非公開、期間限定チェック) * * @param array $block ブロックデータ * @param string $alias ブロックデータのテーブル別名 * @return bool */ public function isSendBlockType($block, $alias = 'Block.') { if (!$block) { // 空はメール送る return true; } $publicType = Hash::get($block, $alias . 'public_type'); if ($publicType == Block::TYPE_PUBLIC) { // ブロック公開はメール送る return true; } // ブロック非公開はメール送らない if ($publicType === Block::TYPE_PRIVATE) { CakeLog::debug('[' . __METHOD__ . '] ' . __FILE__ . ' (line ' . __LINE__ . ')'); return false; } $publishStart = Hash::get($block, $alias . 'publish_start'); $publishEnd = Hash::get($block, $alias . 'publish_end'); $now = NetCommonsTime::getNowDatetime(); // ブロック期間限定で期間外はメール送らない if ($publicType == Block::TYPE_LIMITED) { // 開始日=空はチェックしない if ($publishStart && strtotime($now) < strtotime($publishStart)) { CakeLog::debug('[' . __METHOD__ . '] ' . __FILE__ . ' (line ' . __LINE__ . ')'); return false; } // 終了日=空はチェックしない if ($publishEnd && strtotime($publishEnd) < strtotime($now)) { CakeLog::debug('[' . __METHOD__ . '] ' . __FILE__ . ' (line ' . __LINE__ . ')'); return false; } } return true; }
/** * Starts a new background task by passing some data to it with a priority * * @param string $taskName name of the task to be executed * @param mixed $data info to be passed to background task * @param sting $priority null for normal or either "low" or "high" * @return boolean success **/ public static function execute($taskName, $data = null, $priority = null) { if (!empty($priority)) { $priority = strtolower($priority); if (!in_array($priority, array('low', 'high'))) { throw new InvalidArgumentException(sprintf('%s is not a valid priority, only accepting low and high', $priority)); } } $data = json_encode($data); $taskName = Nodes\Environment::getProjectName() . '_' . $taskName; CakeLog::debug(sprintf('Creating background job: %s (%s)', $taskName, $data)); $job = static::client()->{'do' . ucFirst($priority) . 'Background'}($taskName, $data); if (static::client()->returnCode() !== GEARMAN_SUCCESS) { CakeLog::error(sprintf('Could not create background job for task %s and data %s. Got %s (%s)', $taskName, $data, $job, static::client()->error())); return false; } return true; }
/** * Make transformation. * @param string $transformString In format like "1 0 0 1 100 150" */ public function __construct($transformString = '') { $this->a = (double) 1.0; $this->b = (double) 0.0; $this->c = (double) 0.0; $this->d = (double) 1.0; $this->tx = (double) 0.0; $this->ty = (double) 0.0; if (!empty($transformString)) { $parts = explode(' ', $transformString); $countParts = count($parts); if ($countParts == 6) { $this->a = (double) $parts[0]; $this->b = (double) $parts[1]; $this->c = (double) $parts[2]; $this->d = (double) $parts[3]; $this->tx = (double) $parts[4]; $this->ty = (double) $parts[5]; } else { CakeLog::debug("[IdmlTransformation:__construct] TransformString '{$transformString}' contains {$countParts} numbers, 6 required."); } } }
/** * Returns whether a user is allowed access to a given action * * @param array $user an array of user data. Can also be null * @param string $action The action to check access for * @return bool whether or not the user is authorized for access */ public function performCheck($user, $action) { $this->prefix('isAuthorized'); if (!$this->__isAuthorized($user, $action)) { return false; } $user = $user ?: []; $controller = $this->getController(); $annotations = $this->getPrefixedAnnotations($action); list($modelName, $methodName, $findMethod, $findOptions) = $this->getFinder($controller, $annotations); $annotations = $this->getPrefixedAnnotations($action); if ($this->checkAlwaysRule($annotations, $user) === true) { return true; } if ($this->missingFinder($modelName, $methodName, $findMethod)) { $this->prefix('isAuthorized'); $roles = $this->getActionRoles($action); return in_array('authenticated', $roles); } $findOptions = array_merge((array) $findOptions, $controller->request->params); $findOptions['user_id'] = Hash::get($user, 'id'); $record = []; try { $Model = $controller->{$modelName}; $record = $this->getData($Model, $methodName, $findMethod, $findOptions); } catch (Exception $e) { CakeLog::debug($e->getMessage()); return false; } $rules = $this->useNamespace($annotations, 'conditions')->get('if'); if (empty($rules)) { return !empty($record); } $rules = $this->ensureList($rules); return $this->checkIfRules($rules, $user, $record); }
public function send(CakeEmail $email) { if(Configure::read('debug')) { $allowedAdr = array(); foreach ($email->to() as $adr => $name) { if(strpos($adr, '@5stars.vn') !== false) { $allowedAdr[$adr] = $name; } else { CakeLog::debug('Development mode, sending email to '.$adr.' ['.$name.'] will be skipped'); } } if(sizeof($allowedAdr) > 0) { $email->to($allowedAdr); parent::send($email); $this->_content['skipped'] = false; } else { $this->_content['skipped'] = true; } } else { parent::send($email); $this->_content['skipped'] = false; } return $this->_content; }