/** * Provide an clean environment to render the page * * @param string $targetTpl The compiled PHP resulting file that will be rendered * @param array $assigned Assigned data * * @return string The rendered result */ protected static function isolatedRender($targetTpl, array $assigned) { ob_start(); extract($assigned); unset($assigned); Framework::core('debug')->criticalSection(true); require $targetTpl; Framework::core('debug')->criticalSection(false); return ob_get_clean(); }
/** * The default render when no render has set * * @param string $compiledTpl Path to the compiled template file * @param array $assigned Assigned data * * @return mixed Return the rendered content when succeed, or false otherwise. */ protected static function renderPage($compiledTpl, $assigned) { ob_start(); extract($assigned); unset($assigned); Framework::core('debug')->criticalSection(true); require $compiledTpl; Framework::core('debug')->criticalSection(false); return ob_get_clean(); }
/** * Constructor * * @return void */ public function __construct() { $this->request = Framework::core('request'); }
/** * Get PDO Connection for active query * * @throws Exception\GetConnectionFailed * * @return PDO Return a PDO connection when succeed, or false for fail */ private function getPDOConnection() { if (!($this->connection = Framework::core('pdo')->getConnection(array('Table' => $this->query['From'], 'Operation' => $this->query['Type'])))) { throw new Exception\GetConnectionFailed(); } return $this->connection; }
/** * Perform the server connect * * @return bool Return true when connect, or false when fail */ private function connect() { $conn = null; Framework::core('debug')->criticalSection(true); if ($this->setting['SSL']) { $conn = ftp_ssl_connect($this->setting['Host'], isset($this->setting['Port']) ? $this->setting['Port'] : 21, isset($this->setting['Timeout']) ? $this->setting['Timeout'] : 30); } else { $conn = ftp_connect($this->setting['Host'], isset($this->setting['Port']) ? $this->setting['Port'] : 21, isset($this->setting['Timeout']) ? $this->setting['Timeout'] : 30); } if ($conn) { if (isset($this->setting['Username'][0])) { if (!ftp_login($conn, $this->setting['Username'], isset($this->setting['Password'][0]) ? $this->setting['Password'] : '')) { ftp_close($conn); $conn = null; } else { ftp_pasv($conn, false); } } } Framework::core('debug')->criticalSection(false); if ($conn) { $this->connection = $conn; return true; } return false; }
/** * Connect to a server * * @param string $dbIndex Index number of database server in configure file * @param string $error A reference for storage error detail. * * @return mixed Return PDO object that connected to a database server when success, false otherwise */ protected function doPDOConnect($dbIndex, &$error) { $dbh = null; $successed = false; if (!isset($this->map['DBConn'][$dbIndex]['Connection'])) { // Enter Critical Section so no error below belowing code will cause error Framework::core('debug')->criticalSection(true); try { $dbh = new \PDO($this->pool['DBs'][$dbIndex]['Driver'] . ':' . $this->pool['DBs'][$dbIndex]['Connection'], $this->pool['DBs'][$dbIndex]['Username'], $this->pool['DBs'][$dbIndex]['Password'], array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_TIMEOUT => $this->pool['DBs'][$dbIndex]['Timeout'], \PDO::ATTR_PERSISTENT => $this->pool['DBs'][$dbIndex]['Persistent']) + $this->pool['DBs'][$dbIndex]['Options']); $this->pool['DBs'][$dbIndex]['LstConnected'] = time(); $dbh->_connection =& $this->pool['DBs'][$dbIndex]; $successed = true; } catch (\PDOException $e) { $error = 'PDO Connection failed: Database No.' . $dbIndex . ' Error: ' . $e->getMessage(); new Error('DATABASE_UNAVAILABLE', array($dbIndex, $error), 'NOTICE'); } // Exit Critical Section, restore error caught Framework::core('debug')->criticalSection(false); if ($successed) { $this->map['DBConn'][$dbIndex]['Connection'] =& $dbh; return $this->map['DBConn'][$dbIndex]['Connection']; } } else { return $this->map['DBConn'][$dbIndex]['Connection']; } return false; }
/** * Perform email sending * * @param string $error Reference for error feedback * * @throws RootException * @throws FaculaException * * @return bool Return true when success, or false when fail */ public function send(&$error) { $error = ''; $exception = null; $servers = $this->config['Servers']; Framework::core('debug')->criticalSection(true); try { while (!empty($servers) && !empty($this->emails)) { $currentServer = array_pop($servers); $retryLimit = $currentServer['Retry']; $operatorClassName = static::getOperator($currentServer['Type']); $operator = new $operatorClassName($currentServer, $this->config); while ($retryLimit-- > 0 && !empty($this->emails)) { if (!$operator->connect($error)) { $error .= ' on server: ' . $currentServer['Host']; } while (!empty($this->emails)) { $currentEmail = array_pop($this->emails); if ($operator->send($currentEmail, $error)) { continue; } array_push($this->emails, $currentEmail); $error .= ' on server: ' . $currentServer['Host']; break; } $operator->disconnect(); } } } catch (FaculaException $e) { Framework::core('debug')->criticalSection(false); $exception = $e; } catch (RootException $e) { // For fsockopen error etc Framework::core('debug')->criticalSection(false); $exception = $e; } Framework::core('debug')->criticalSection(false); if ($exception !== null) { throw $exception; } if ($error) { return false; } return true; }
/** * Execute the handler to upload file * * @param OperatorImplement $handler instance * @param string $localFile Path to the file * @param string $remoteFileName Name of this file on remote server * @param string $error Error detail * * @throws Exception\HandlerException * * @return mixed Return path on the remote server when success, false otherwise */ protected static function runHandler(OperatorImplement $handler, $localFile, $remoteFileName, &$error) { $result = false; $exception = null; Framework::core('debug')->criticalSection(true); try { $result = $handler->upload($localFile, $remoteFileName, $error); } catch (PHPException $e) { $exception = $e; } Framework::core('debug')->criticalSection(false); if ($exception !== null) { throw new Exception\HandlerException($exception->getMessage()); } return $result; }
/** * Perform email sending * * @return bool Return true when success, or false when fail */ public static function sendMail() { $operater = null; $operaterClassName = $error = ''; $remainingMails = count(static::$emails); $retryLimit = 3; $currentServers = array(); if (!empty(static::$config) && $remainingMails > 0) { $currentServers = static::$config['Servers']; Framework::core('debug')->criticalSection(true); while (!empty($currentServers) && !empty(static::$emails) && $retryLimit > 0) { foreach ($currentServers as $serverkey => $server) { $operaterClassName = static::getOperator($server['Type']); if (class_exists($operaterClassName)) { $operater = new $operaterClassName($server); if ($operater instanceof Base) { if ($operater->connect($error)) { foreach (static::$emails as $mailkey => $email) { if ($operater->send($email)) { unset(static::$emails[$mailkey]); } else { $retryLimit--; break; // There is no point to continue try this connection // to send another email after fail. } } $operater->disconnect(); } else { $error .= ' on server: ' . $server['Host']; unset($currentServers[$serverkey]); } } else { throw new Exception\OperatorExtendsInvalid($operaterClassName); } } else { throw new Exception\OperatorClassNotFound($operaterClassName, $server['Type']); } } } Framework::core('debug')->criticalSection(false); if (!$error) { return true; } } return false; }
/** * Save data to cache * * @param string $cacheName Cache name * @param string $data Data will be saved in cache * @param string $expire How long (in second) the cache will expired after saving * * @return bool Return true success, false otherwise */ public function save($cacheName, $data, $expire = 0) { $cacheData = array(); $expireMethod = null; $expiredTime = 0; if ($path = $this->getCacheFileByName($cacheName)) { $file = $this->configs['Root'] . DIRECTORY_SEPARATOR . $path['File']; if ($expire) { if ($expire > FACULA_TIME) { $expireMethod = 2; } switch ($expireMethod) { case 2: // expireMethod = scheduled. // The cache will expired when reach specified date $expiredTime = $expire; break; default: // expireMethod = remaining. // The cache will expired when remaining time come to zero. $expiredTime = FACULA_TIME + $expire; break; } } if ($this->makeCacheDir($path['Path'])) { $cacheData = array(0 => (int) $expiredTime, 1 => $this->configs['BootVer'], 2 => $data ? $data : null); Framework::core('debug')->criticalSection(true); if (file_exists($file)) { unlink($file); } Framework::core('debug')->criticalSection(false); return file_put_contents($file, static::$setting['CacheFileSafeCode'][0] . ' $cache = ' . var_export($cacheData, true) . '; ' . static::$setting['CacheFileSafeCode'][1]); } } return false; }
/** * Call path handler * * @param array $callParameter The combined class and method name * @param array $parameters Parameters used for calling * @param bool $cacheCall Make object function core cache the class instance * @param integer $failType Reference output for fail type * * @return mixed Return false on false, return the calling result otherwise */ protected static function call(array $callParameter, array $parameters, $cacheCall, &$failType) { $callResult = null; switch ($callParameter[static::CALL_STRING_TYPE]) { case static::CALL_TYPE_STATIC: $callResult = Framework::core('object')->callFunction(array($callParameter[static::CALL_STRING_CLASS], $callParameter[static::CALL_STRING_METHOD]), $parameters); break; case static::CALL_TYPE_INSTANCE: $callResult = Framework::core('object')->callFunction(array(Framework::core('object')->getInstance($callParameter[static::CALL_STRING_CLASS], array(), $cacheCall), $callParameter[static::CALL_STRING_METHOD]), $parameters); break; case static::CALL_TYPE_METHOD: $instance = Framework::core('object')->getInstance($callParameter[static::CALL_STRING_CLASS], array(), $cacheCall); $accessMethod = Framework::core('request')->getClientInfo('method'); if (!isset(static::$allowedMethods[$accessMethod])) { $failType = static::HANDLER_FAIL_NOT_ALLOWED; return false; } if (!method_exists($instance, $accessMethod)) { $failType = static::HANDLER_FAIL_NO_HANDLER; return false; } $callResult = Framework::core('object')->callFunction(array($instance, $accessMethod), $parameters); break; default: break; } if ($callResult) { return $callResult; } $failType = static::HANDLER_FAIL_RESULT_FALSE; return false; }
/** * Add log into log file or record pool * * @param string $type Type of this error * @param string $errorCode Error code * @param string $content Message of the error * @param array $backTraces Reference Data of Back Traces * * @return bool true when log saved, false otherwise */ public function addLog($type, $errorCode, $content = '', &$backTraces = array()) { $time = microtime(true); $date = date(DATE_ATOM, $time); $ip = Framework::core('request')->getClientInfo('ip'); if (!$this->configs['LogRoot']) { return false; } $dateFileName = date('Y-m-d H', $time); $errorType = '[' . strtoupper($type) . ']' . ($errorCode ? ':' . $errorCode : ''); $filename = 'log.' . $dateFileName . '.php'; $format = "<?php exit(); ?> {$errorType} {$ip} ({$date}): {$content}"; return file_put_contents($this->configs['LogRoot'] . Framework::DIRECTORY_SEPARATOR . $filename, $format . "\r\n", FILE_APPEND | LOCK_EX); }
/** * Upload a file * * @param string $localFile Path to file that needs to be uploaded * @param string $remotePath Target path (not including file name) on remote server * @param string $remoteFileName File name * * @return string Return Path to the file on remote FTP server (/ftproot/blablabla/file1.txt) */ public function upload($localFile, $remotePath, $remoteFileName) { $server = array(); $path = $currentRemotePath = $resultPath = ''; if ($server = $this->getCurrentServer()) { if (isset($server['Path']) && !$this->doEnterPath($server['Path'] . '/' . $remotePath, $currentRemotePath)) { trigger_error('ERROR_FTP_CHANGEDIR_FAILED', E_USER_ERROR); } Framework::core('debug')->criticalSection(true); if (is_readable($localFile)) { if (ftp_put(self::$connection, $remoteFileName, $localFile, FTP_BINARY)) { $resultPath = $currentRemotePath . '/' . $remoteFileName; } } else { trigger_error('ERROR_FTP_FILE_UNREADABLE|' . $localFile, E_USER_ERROR); } Framework::core('debug')->criticalSection(false); } return $resultPath; }