/** * launches the book build process * @param int $chaucerBookId * @return boolean */ public function runBookProcess() { $bookSource = $this->getBookSourceType(); if (!$bookSource) { throw new Exception("Book {$this->bookId} not found in chaucer database."); } $objProcessor = $this->getBookProcessor($bookSource); if (is_object($objProcessor)) { $objProcessor->progressBookId = $this->updateBookId; $objProcessor->completedState = $this->completedState; $objProcessor->uploadedFiles = $this->sourceFiles; try { return $objProcessor->process(); } catch (Exception $e) { $msg = trim($e->getMessage()); if (strlen($msg) > 0) { if (substr($msg, 0, 1) == '[') { $displayMsg = substr($msg, strpos($msg, ']') + 1); } else { $displayMsg = $msg; } } if (is_object($objProcessor->progress)) { CakeLog::error($e->getMessage()); $objProcessor->processError($displayMsg); } else { trigger_error($e->getMessage(), E_USER_ERROR); } } } else { throw new Exception('[ProcessQueue::runBookProcess] Unknown book source'); } return false; }
/** * 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; }
/** * Save questionnaire settings * * @param array $data received post data * @return bool True on success, false on failure * @throws InternalErrorException */ public function saveQuestionnaireBlocksSetting($data) { $this->loadModels(['BlockRolePermission' => 'Blocks.BlockRolePermission']); //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); try { if (!$this->validateQuestionnaireBlocksSetting($data)) { return false; } foreach ($data[$this->BlockRolePermission->alias] as $value) { if (!$this->BlockRolePermission->validateBlockRolePermissions($value)) { $this->validationErrors = Hash::merge($this->validationErrors, $this->BlockRolePermission->validationErrors); return false; } } if (!$this->save(null, false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } foreach ($data[$this->BlockRolePermission->alias] as $value) { if (!$this->BlockRolePermission->saveMany($value, ['validate' => false])) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * view * * @return void * @throws Exception */ public function view() { if (!Current::read('Block.id')) { $this->autoRender = false; return; } $isAccessed = 'block_key_' . Current::read('Block.key'); //AccessCounterFrameSettingデータ取得 $counterFrameSetting = $this->AccessCounterFrameSetting->getAccessCounterFrameSetting(true); $this->set('accessCounterFrameSetting', $counterFrameSetting['AccessCounterFrameSetting']); //AccessCounterデータ取得 $accessCounter = $this->AccessCounter->getAccessCounter(true); // カウントアップ処理 if (!$this->Session->read($isAccessed)) { try { $this->AccessCounter->updateCountUp($accessCounter); $accessCounter['AccessCounter']['count']++; // アクセス情報を記録 $this->Session->write($isAccessed, CakeSession::read('Config.userAgent')); } catch (Exception $ex) { CakeLog::error($ex); throw $ex; } } $this->set('accessCounter', $accessCounter['AccessCounter']); }
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'); }
/** * Uninstall plugin * * @param Model $model Model using this behavior * @param array $data Plugin data * @return bool True on success * @throws InternalErrorException */ public function uninstallPlugin(Model $model, $data) { $model->loadModels(['Plugin' => 'PluginManager.Plugin', 'PluginsRole' => 'PluginManager.PluginsRole', 'PluginsRoom' => 'PluginManager.PluginsRoom']); //トランザクションBegin $model->setDataSource('master'); $dataSource = $model->getDataSource(); $dataSource->begin(); if (is_string($data)) { $key = $data; } else { $key = $data[$model->alias]['key']; } try { //Pluginの削除 if (!$model->deleteAll(array($model->alias . '.key' => $key), false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //PluginsRoomの削除 if (!$model->PluginsRoom->deleteAll(array($model->PluginsRoom->alias . '.plugin_key' => $key), false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //PluginsRoleの削除 if (!$model->PluginsRole->deleteAll(array($model->PluginsRole->alias . '.plugin_key' => $key), false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * PING * * @param string|null $url pingのURL(テストで使用する) * @return mixed fsockopenの結果 */ public function ping($url = null) { //サイトの生死確認 $errno = 0; $errstr = null; if (!$url) { $url = self::NOTIFICATION_PING_URL; } CakeLog::info('Execute ping ' . $url); try { $resource = fsockopen($url, 80, $errno, $errstr, 3); } catch (Exception $ex) { $resource = false; CakeLog::error($ex); } if (!$resource) { CakeLog::info('Failure ping ' . $url); $result = false; } else { fclose($resource); $result = true; CakeLog::info('Success ping ' . $url); } return $result; }
/** * Move Order UserAttributes * * @param array $data received post data * @return bool True on success, false on validation errors * @throws InternalErrorException */ public function saveUserAttributesOrder($data) { //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); try { ////バリデーション //$indexes = array_keys($data['LinkOrders']); //foreach ($indexes as $i) { // if (! $this->validateLinkOrder($data['LinkOrders'][$i])) { // return false; // } //} // ////登録処理 //foreach ($indexes as $i) { // if (! $this->save($data['LinkOrders'][$i], false, false)) { // throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); // } //} //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * save blog * * @param array $data received post data * @return mixed On success Model::$data if its not empty or true, false on failure * @throws InternalErrorException */ public function saveBlogFrameSetting($data) { $this->loadModels(['BlogFrameSetting' => 'Blogs.BlogFrameSetting']); //トランザクションBegin $dataSource = $this->getDataSource(); $dataSource->begin(); try { //バリデーション if (!$this->validateBlogFrameSetting($data)) { $dataSource->rollback(); return false; } //登録処理 if (!($resultData = $this->save(null, false))) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return $resultData; }
/** * 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); $this->_loadFixtures($fixtures); CakeLog::debug('Begin fixture import'); CakeLog::debug(''); $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::notice('-> Can not find it in the loaded array.. weird'); continue; } $fixture = $this->_loaded[$f]; CakeLog::debug(sprintf('-> Found fixture: %s', get_class($fixture))); $this->_setupTable($fixture, $this->_db, true); CakeLog::debug('-> Created table "OK"'); if ($fixture->insert($this->_db)) { CakeLog::debug('-> Inserted fixture data "OK"'); } else { CakeLog::error('-> Inserted fixture data "ERROR"'); } CakeLog::debug(''); } $this->_db->commit(); $this->_useNestedTransactions = $nested; CakeLog::debug('Done!'); }
public function lookup($url) { $results = $this->http->get($url); if (!$results->isOk()) { CakeLog::error("GooglePlayApi::lookup: Error: {$url} {$results->reasonPhrase} {$results->body}"); return false; } $results = $this->parseHtml($results->body); return $results; }
public function rotate() { try { $this->_rotate($this->config); } catch (Exception $e) { CakeLog::error('LogRotation::rotate() - ' . $e->getMessage(), 'backend'); return false; } return true; }
public function saveTest() { $data['Test'] = $this->request->data; // CakeLog::error(print_r($data, true)); if ($this->Test->save($data)) { $this->Session->setFlash('Your post has been saved.'); $this->redirect(array('controller' => 'departments', 'action' => 'viewTime', $data['Test']['department_id'])); } else { $this->Session->setFlash('Unable to add your post.'); CakeLog::error($this->Test->validationErrors); } }
public function parse() { libxml_clear_errors(); $xml_string = trim(file_get_contents($this->path)); try { $this->xml = new SimpleXMLElement($xml_string); return true; } catch (Exception $e) { CakeLog::error("Unable to parse TOC: " . implode(', ', libxml_get_errors())); return false; } }
public function create($db) { $ok = parent::create($db); // Workaround: CakeSchema cannot create FULLTEXT fixtures, so we change the table manually after creation if ($ok) { $query = "ALTER TABLE `{$this->table}` ADD FULLTEXT INDEX `data` (`data` ASC)"; try { $db->rawQuery($query); $this->created[] = $db->configKeyName; } catch (Exception $e) { $msg = __d('cake_dev', 'Fixture creation for "%s" failed "%s"', $this->table, $e->getMessage()); CakeLog::error($msg); trigger_error($msg, E_USER_WARNING); return false; } return true; } return false; }
/** * Load Event Handlers during bootstrap. * * Plugins can add their own custom EventHandler in Config/events.php * with the following format: * * $config = array( * 'EventHandlers' => array( * 'Example.ExampleEventHandler' => array( * 'eventKey' => null, * 'options' => array( * 'priority' => 1, * 'passParams' => false, * 'className' => 'Plugin.ClassName', * ))); * * @return void */ public static function loadListeners() { $eventManager = CroogoEventManager::instance(); $cached = Cache::read('EventHandlers', 'cached_settings'); if ($cached === false) { $eventHandlers = Configure::read('EventHandlers'); $validKeys = array('eventKey' => null, 'options' => array()); $cached = array(); if (!empty($eventHandlers) && is_array($eventHandlers)) { foreach ($eventHandlers as $eventHandler => $eventOptions) { $eventKey = null; if (is_numeric($eventHandler)) { $eventHandler = $eventOptions; $eventOptions = array(); } list($plugin, $class) = pluginSplit($eventHandler); if (!empty($eventOptions)) { extract(array_intersect_key($eventOptions, $validKeys)); } if (isset($eventOptions['options']['className'])) { list($plugin, $class) = pluginSplit($eventOptions['options']['className']); } App::uses($class, $plugin . '.Event'); if (class_exists($class)) { $cached[] = compact('plugin', 'class', 'eventKey', 'eventOptions'); } else { CakeLog::error(__d('croogo', 'EventHandler %s not found in plugin %s', $class, $plugin)); } } Cache::write('EventHandlers', $cached, 'cached_settings'); } } foreach ($cached as $cache) { extract($cache); if (CakePlugin::loaded($plugin)) { App::uses($class, $plugin . '.Event'); $settings = isset($eventOptions['options']) ? $eventOptions['options'] : array(); $listener = new $class($settings); $eventManager->attach($listener, $eventKey, $eventOptions); } } }
/** * ブロック一覧表示 * * @return CakeResponse * @throws Exception */ public function index() { $this->Paginator->settings = array('VideoBlockSetting' => array('order' => array('VideoBlockSetting.id' => 'desc'), 'joins' => array(array('type' => 'LEFT', 'table' => '( SELECT b.key, SUM(f.size) size_byte' . ' FROM videos v, blocks b, files f' . ' WHERE v.block_id = b.id' . ' AND (v.mp4_id = f.id OR v.thumbnail_id = f.id)' . " AND b.plugin_key = '" . $this->request->params['plugin'] . "'" . ' GROUP BY b.key )', 'alias' => 'Size', 'conditions' => 'VideoBlockSetting.block_key = Size.key')), 'conditions' => array('Block.key = VideoBlockSetting.block_key', 'Block.language_id' => $this->viewVars['languageId'], 'Block.room_id' => $this->viewVars['roomId']), 'fields' => array('*', 'Size.size_byte'))); try { if (!($videoBlockSetting = $this->Paginator->paginate('VideoBlockSetting'))) { $this->view = 'not_found'; return; } } catch (Exception $ex) { if (isset($this->request['paging']) && $this->params['named']) { $this->redirect('/videos/video_block_settings/index/' . $this->viewVars['frameId']); return; } CakeLog::error($ex); throw $ex; } $results['videoBlockSettings'] = $videoBlockSetting; $results = $this->camelizeKeyRecursive($results); $this->set($results); }
/** * Execute Task * @return bool */ public function execute() { $this->out(' >> Email Task', 1, Shell::VERBOSE); /** * Exit if no message id */ if (empty($this->message_id) || empty($this->ddb)) { $this->out(' Failed. No Message id.'); return false; } $message_data = $this->ddb->getData($this->message_id); /** * Exit if no data */ if (empty($message_data)) { $this->out(' Failed. No Message data.', 1, Shell::NORMAL); return false; } $payload = $message_data['payload']; $to = $payload['to']; $locale = $payload['locale']; $data = $payload['email_data']; $template = $payload['template']; $tag = $payload['tag']; $subject = $payload['subject']; $emailOptions = $payload['email_options']; try { /** * Send user email */ $this->out(' Sending Email.', 1, Shell::VERBOSE); $this->sendEmail($data, $to, $locale, $template, $tag, $subject, $emailOptions); } catch (Exception $e) { $this->out(' Failed.'); CakeLog::error('CRITICAL: Error encountered in Email Task'); CakeLog::error($e->getMessage()); return false; } $this->out(' Done.', 1, Shell::VERBOSE); return true; }
/** * Convert XML file to DOMDocument and validate against Edexml XSD * * @param string $filename Filename of XML file * @return mixed A DOMDocument (DOMDocument), or false (boolean) on validation errors */ protected function _parse($filename) { $dom = false; if (file_exists($filename)) { // Enable user error handling libxml_use_internal_errors(true); libxml_clear_errors(); $dom = Xml::build($filename, ['return' => 'domdocument']); if ($dom) { $schemaFile = CakePlugin::path('Edexml') . 'File' . DS . 'EDEXML-2.0' . DS . 'EDEXML.structuur.xsd'; if (!$dom->schemaValidate($schemaFile)) { $dom = false; foreach (libxml_get_errors() as $error) { CakeLog::error($this->_displayXmlError($error), 'debug'); } libxml_clear_errors(); } } } return $dom; }
/** * Save topic * * @param array $data received post data * @return mixed On success Model::$data if its not empty or true, false on failure * @throws InternalErrorException */ public function saveTopic($data) { $con = $this->getDataSource(); $con->begin(); try { $this->Topic = ClassRegistry::init('Topics.Topic'); if (!$this->Topic->validateTopic(['block_id' => $data['block_id'], 'status' => $data['status'], 'is_active' => $data['is_active'], 'is_latest' => $data['is_latest'], 'is_auto_translated' => $data['is_auto_translated'], 'is_first_auto_translation' => $data['is_first_auto_translation'], 'translation_engine' => $data['translation_engine'], 'title' => Search::prepareTitle($data['contents']), 'contents' => Search::prepareContents([$data['contents']]), 'plugin_key' => $data['plugin_key'], 'path' => $data['path'], 'from' => $data['from']])) { $this->validationErrors = Hash::merge($this->validationErrors, $this->Topic->validationErrors); return false; } if (!$this->Topic->save(null, false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } $con->commit(); } catch (Exception $ex) { $con->rollback(); CakeLog::error($ex); throw $ex; } /* return $announcement; */ }
/** * index * * @return void */ public function index() { if (!$this->Notification->validCacheTime() && !$this->Session->read('getNotificationError')) { try { $this->Session->write('getNotificationError', true); //サイトの生死確認 if ($this->Notification->ping()) { $notifications = $this->Notification->serialize(); //更新処理 $this->Notification->updateNotifications(array('Notification' => $notifications)); $this->Session->write('getNotificationError', false); } } catch (XmlException $e) { // Xmlが取得できなくても、エラーにしない CakeLog::error($e); } } $notifications = $this->Notification->find('all', array('recursive' => -1, 'limit' => Notification::MAX_ROW, 'order' => array('modified' => 'desc'))); $this->set('notifications', $notifications); $this->set('title', __d('notifications', 'Notifications')); }
public function lookup($url) { $_url = parse_url($url); if ($_url == false) { CakeLog::error("AppStoreApi::lookup error: url={$url}"); return false; } $path = explode('/', $_url['path']); foreach ($path as $p) { if (preg_match('/id([0-9]+)/', $p, $m)) { $id = $m[1]; break; } } $res = $this->http->get('https://itunes.apple.com/jp/lookup', compact('id')); if (!$res->isOk()) { CakeLog::error("AppStoreApi::lookup error: url={$url} code={$res->code}"); return false; } $result = json_decode($res->body, true); return $result['results'][0]; }
/** * Save plugin * * @param array $data Request data * @return bool True on success * @throws InternalErrorException */ public function saveUserAttributeLayout($data) { $this->loadModels(['UserAttributeLayout' => 'UserAttributes.UserAttributeLayout']); //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); try { //AttributeLayoutテーブルの登録 if (!$this->save($data)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * save RssReaderFrameSetting * * @param array $data received post data * @return bool true success, false error * @throws InternalErrorException */ public function saveRssReaderFrameSetting($data) { $this->loadModels(['RssReaderFrameSetting' => 'RssReaders.RssReaderFrameSetting']); //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); try { //validate処理 if (!$this->validateRssReaderFrameSetting($data)) { return false; } //登録処理 if (!$this->save(null, false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } $dataSource->commit(); } catch (Exception $ex) { $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * login * * @return void * @throws InternalErrorException **/ public function login() { if ($this->request->is('post')) { if ($this->Auth->login()) { //トランザクションBegin $this->User->setDataSource('master'); $dataSource = $this->User->getDataSource(); $dataSource->begin(); try { $update = array('User.last_login' => '\'' . date('Y-m-d H:i:s') . '\''); $conditions = array('User.id' => (int) $this->Auth->user('id')); $this->User->updateAll($update, $conditions); $dataSource->commit(); } catch (Exception $ex) { $dataSource->rollback(); CakeLog::error($ex); throw $ex; } $this->redirect($this->Auth->redirect()); } $this->Flash->set(__d('auth', 'Invalid username or password, try again')); $this->redirect($this->Auth->loginAction); } }
/** * Save menu frame setting * * @param array $data received post data * @return bool True on success, false on failure * @throws InternalErrorException */ public function saveMenuFrameSetting($data) { $this->loadModels(['MenuFrameSetting' => 'Menus.MenuFrameSetting', 'MenuFramesPage' => 'Menus.MenuFramesPage']); //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); if (!$this->validateMenuFrameSetting($data['MenuFrameSetting'])) { return false; } if (!$this->MenuFramesPage->validateMany($data['Menus'])) { $this->validationErrors = Hash::merge($this->validationErrors, $this->MenuFramesPage->validationErrors); return false; } try { //MenuFrameSetting登録処理 if (!$this->save($data['MenuFrameSetting'], false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //MenuFramesPage登録処理 foreach ($data['Menus'] as $menu) { if (!$this->MenuFramesPage->save($menu['MenuFramesPage'], false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); //エラー出力 CakeLog::error($ex); throw $ex; } return true; }
/** * Generate tided HTML code * * @param string $content * @return string modified content if avaible, otherwise origin content */ public static function tidy($content, $options = array()) { $options += array('tidy' => dirname(__DIR__) . DS . 'Vendor' . DS . 'tidy-html5' . DS . 'bin' . DS . 'tidy'); if (!is_executable($options['tidy'])) { CakeLog::error('Tidy not executable.'); return $content; } $configFile = self::_config($options); $origFile = CACHE . md5($content); $tidedFile = CACHE . 'tided_' . md5($content); if (is_writeable(dirname($origFile)) && $configFile) { if (file_put_contents($origFile, $content)) { exec($options['tidy'] . ' -config ' . $configFile . ' ' . $origFile . ' > ' . $tidedFile); if (file_exists($tidedFile)) { $tidedContent = file_get_contents($tidedFile); unlink($tidedFile); } else { $tidedContent = null; } unlink($origFile); } } return empty($tidedContent) ? $content : $tidedContent; }
/** * Delete RolesRoomsUser * * @param array $data received post data * @return mixed On success Model::$data if its not empty or true, false on failure * @throws InternalErrorException */ public function deleteRolesRoomsUser($data) { //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); try { //Roomデータの削除 if (!$this->delete($data['RolesRoomsUser']['id'], false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * Get url * * @return void */ public function get() { $url = Hash::get($this->request->query, 'url'); if (!$url) { return false; } try { $socket = new HttpSocket(array('request' => array('redirect' => 10))); $response = $socket->get($url); if (!$response->isOk()) { $this->throwBadRequest(__d('links', 'Failed to obtain the title for this page.')); return; } } catch (SocketException $ex) { CakeLog::error($ex); $this->throwBadRequest(__d('links', 'Failed to obtain the title for this page.')); return; } $results = array('title' => null, 'description' => null); $body = $response->body; $pattern = '/<title>(.*)<\\/title>/i'; $matches = array(); if (preg_match($pattern, $body, $matches)) { $results['title'] = mb_convert_encoding($matches[1], 'utf-8', 'auto'); } $pattern = '/<meta[^"\'<>\\]]*name=([\'"]?)description\\1[^"\'<>\\]]*content=([\'"]?)([^"\'<>\\]]*)\\2[^"\'<>\\]]*>/i'; $matches = array(); if (preg_match($pattern, $body, $matches)) { $results['description'] = mb_convert_encoding($matches[3], 'utf-8', 'auto'); } $this->NetCommons->renderJson($results); }
/** * AWS S3のファイルをコピーする * * @param string $srcFilePath 移動元のファイル * @param string $dstFilePath 移動先のファイル * @return mixed */ protected function copyFile($srcFilePath, $dstFilePath) { // 行頭にスラッシュが入っていた場合は消す $srcFilePath = preg_replace("/^\\/(.+)\$/", "\$1", $srcFilePath); $dstFilePath = preg_replace("/^\\/(.+)\$/", "\$1", $dstFilePath); try { $this->S3->copyObject(array('Bucket' => $this->bucketName, 'CopySource' => $this->bucketName . '/' . $srcFilePath, 'Key' => $dstFilePath, 'ACL' => CannedAcl::PUBLIC_READ)); } catch (Exception $e) { CakeLog::error('AWS S3 [copyObject]: ' . $exc->getMessage()); return false; } return true; }