/** * {@inheritdoc} */ public function get($key) { self::$logger->debug('>>get(key=[' . $key . '])'); try { $value = apc_fetch($key); self::$logger->debug('<<get: [' . print_r($value, true) . '])'); return $value; } catch (\Exception $e) { self::$logger->error('Error while attempting to load a business object from APC cache: [' . $e->getMessage() . ']'); self::$logger->debug('<<get: [false])'); return false; } }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $body = View::displayPageHead($this); $sequence = new Sequence(); // make sure that the Sequence tables exist if (!$sequence->checkTableExists()) { $body .= View::displayErrorMessage('Warning! The Sequence table do not exist, attempting to create it now...'); $sequence->makeTable(); } // set the start point for the list pagination if (isset($params['start']) ? $this->startPoint = $params['start'] : ($this->startPoint = 1)) { } $records = $sequence->loadAll($this->startPoint); ActiveRecord::disconnect(); $this->BOCount = $sequence->getCount(); $body .= View::renderDeleteForm($this->request->getURI()); foreach ($records as $record) { $view = View::getInstance($record); $body .= $view->listView(array('URI' => $request->getURI())); } $body .= View::displayPageFoot($this); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Login the user and re-direct to the defined destination. * * @param string $password The password supplied by the user logging in * * @throws Alpha\Exception\ValidationException * * @return Alpha\Util\Http\Response * * @since 1.0 */ protected function doLoginAndRedirect($password) { self::$logger->debug('>>doLoginAndRedirect(password=[' . $password . '])'); $config = ConfigProvider::getInstance(); if (!$this->personObject->isTransient() && $this->personObject->get('state') == 'Active') { if (password_verify($password, $this->personObject->get('password'))) { $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); $session->set('currentUser', $this->personObject); self::$logger->debug('Logging in [' . $this->personObject->get('email') . '] at [' . date('Y-m-d H:i:s') . ']'); self::$logger->action('Login'); $response = new Response(301); if ($this->getNextJob() != '') { $response->redirect(FrontController::generateSecureURL('act=' . $this->getNextJob())); $this->clearUnitOfWorkAttributes(); } else { $response->redirect($config->get('app.url')); } return $response; } else { throw new ValidationException('Failed to login user ' . $this->personObject->get('email') . ', the password is incorrect!'); self::$logger->debug('<<doLoginAndRedirect'); } } }
/** * Overrides the TCPDF::Image method to decrypt encrypted $file paths from the Image widget, then pass * them to the normal TCPDF::Image along with all of the other (unmodified) parameters. * * @param string $file Name of the file containing the image. * @param float $x Abscissa of the upper-left corner. * @param float $y Ordinate of the upper-left corner. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension. * @param mixed $link URL or identifier returned by AddLink(). * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param bool $resize If true resize (reduce) the image to fit $w and $h (requires GD library). * @param int $dpi dot-per-inch resolution used on resize * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @param bool $ismask true if this image is a mask, false otherwise * @param mixed $imgmask image object returned by this function or false * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> * * @since 1.0 */ public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300, $palign = '', $ismask = false, $imgmask = false, $border = 0) { if (self::$logger == null) { self::$logger = new Logger('TCPDF'); } $config = ConfigProvider::getInstance(); self::$logger->debug('Processing image file URL [' . $file . ']'); try { if (mb_strpos($file, '/tk/') !== false) { $start = mb_strpos($file, '/tk/') + 3; $end = mb_strlen($file); $tk = mb_substr($file, $start + 1, $end - ($start + 1)); $decoded = FrontController::getDecodeQueryParams($tk); parent::Image($decoded['source'], $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border); } else { // it has no query string, so threat as a regular image URL if (Validator::isURL($file)) { parent::Image($config->get('app.root') . '/' . Image::convertImageURLToPath($file), $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border); } else { parent::Image($file, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border); } } } catch (\Exception $e) { self::$logger->error('Error processing image file URL [' . $file . '], error [' . $e->getMessage() . ']'); throw $e; } }
/** * Loops over the /tasks directory and builds an array of all of the task * class names in the system. * * @return array * * @since 1.0 */ public static function getTaskClassNames() { $config = ConfigProvider::getInstance(); if (self::$logger == null) { self::$logger = new Logger('CronManager'); self::$logger->setLogFile($config->get('app.file.store.dir') . 'logs/tasks.log'); } self::$logger->debug('>>getTaskClassNames()'); $classNameArray = array(); if (file_exists($config->get('app.root') . 'Task')) { $handle = opendir($config->get('app.root') . 'Task'); // loop over the custom task directory while (false !== ($file = readdir($handle))) { if (preg_match('/Task.php/', $file)) { $classname = mb_substr($file, 0, -4); array_push($classNameArray, $classname); } } } if (file_exists($config->get('app.root') . 'Alpha/Task')) { $handle = opendir($config->get('app.root') . 'Alpha/Task'); // loop over the custom task directory while (false !== ($file = readdir($handle))) { if (preg_match('/Task.php/', $file)) { $classname = mb_substr($file, 0, -4); array_push($classNameArray, $classname); } } } self::$logger->debug('<<getTaskClassNames [' . var_export($classNameArray, true) . ']'); return $classNameArray; }
/** * Method to handle DELETE requests. * * @param Alpha\Util\Http\Request * * @return Alpha\Util\Http\Response * * @since 2.0 */ public function doDELETE($request) { self::$logger->debug('>>doDELETE($request=[' . var_export($request, true) . '])'); $this->setUnitOfWork(array()); self::$logger->debug('<<doDELETE'); return parent::doDELETE($request); }
/** * Parses a MySQL error for the value that violated a unique constraint. * * @param string $error The MySQL error string. * * @since 1.1 */ private function findOffendingValue($error) { self::$logger->debug('>>findOffendingValue(error=[' . $error . '])'); $singleQuote1 = mb_strpos($error, "'"); $singleQuote2 = mb_strrpos($error, "'"); $value = mb_substr($error, $singleQuote1, $singleQuote2 - $singleQuote1 + 1); self::$logger->debug('<<findOffendingValue [' . $value . '])'); return $value; }
/** * A static method that attempts to return a CacheProviderInterface instance * based on the name of the provider class supplied. * * @param $providerName The class name of the provider class (fully qualified). * * @throws Alpha\Exception\IllegalArguementException * * @return Alpha\Util\Cache\CacheProviderInterface * * @since 1.1 */ public static function getInstance($providerName) { if (self::$logger == null) { self::$logger = new Logger('CacheProviderFactory'); } self::$logger->debug('>>getInstance(providerName=[' . $providerName . '])'); if (class_exists($providerName)) { $instance = new $providerName(); if (!$instance instanceof CacheProviderInterface) { throw new IllegalArguementException('The class [' . $providerName . '] does not implement the expected CacheProviderInterface intwerface!'); } self::$logger->debug('<<getInstance: [Object ' . $providerName . ']'); return $instance; } else { throw new IllegalArguementException('The class [' . $providerName . '] is not defined anywhere!'); } self::$logger->debug('<<getInstance'); }
/** * A static method that attempts to return a RendererProviderInterface instance * based on the name of the provider class supplied. * * @param $providerName The fully-qualified class name of the provider class, must implement Alpha\View\Renderer\RendererProviderInterface. * @param $BO The Alpha\Model\ActiveRecord instance to pass to the renderer provider for passing data. * * @throws Alpha\Exception\IllegalArguementException * * @return Alpha\View\Renderer\RendererProviderInterface * * @since 1.2 */ public static function getInstance($providerName, $BO = null) { if (self::$logger == null) { self::$logger = new Logger('RendererProviderFactory'); } self::$logger->debug('>>getInstance(providerName=[' . $providerName . '])'); if (!class_exists($providerName)) { throw new IllegalArguementException('The class [' . $providerName . '] is not defined anywhere!'); } $instance = new $providerName(); if (isset($BO)) { $instance->setBO($BO); } if (!$instance instanceof RendererProviderInterface) { throw new IllegalArguementException('The class [' . $providerName . '] does not implement the expected AlphaRendererProviderInterface interface!'); } self::$logger->debug('<<getInstance: [Object ' . $providerName . ']'); return $instance; }
/** * Handle DELETE requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\SecurityException * @throws Alpha\Exception\IllegalArguementException * * @since 2.0 */ public function doDELETE($request) { self::$logger->debug('>>doDELETE($request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $this->setName($config->get('app.url') . $this->request->getURI()); $this->setUnitOfWork(array($config->get('app.url') . $this->request->getURI(), $config->get('app.url') . $this->request->getURI())); $request->addParams(array('ActiveRecordType' => 'Alpha\\Model\\Tag')); self::$logger->debug('<<doDELETE'); return parent::doDELETE($request); }
/** * {@inheritdoc} */ public function send($to, $from, $subject, $body, $isHTML = false) { self::$logger->debug('>>send(to=[' . $to . '], from=[' . $from . '], subject=[' . $subject . '], body=[' . $body . '], isHTML=[' . $isHTML . '])'); $config = ConfigProvider::getInstance(); $headers = 'MIME-Version: 1.0' . "\n"; if ($isHTML) { $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n"; } $headers .= 'From: ' . $from . "\n"; if ($config->getEnvironment() != 'dev') { try { mb_send_mail($to, $subject, $body, $headers); } catch (PHPException $e) { throw new MailNotSentException('Error sending a mail to [' . $to . ']'); } } else { self::$logger->info("Sending email:\n" . $headers . "\n" . $body); } self::$logger->debug('<<send'); }
/** * Handles get requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 * * @throws Alpha\Exception\ResourceNotFoundException */ public function doGet($request) { self::$logger->debug('>>doGet(request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $relationObject = new Relation(); $body = ''; try { $relationType = $params['relationType']; $ActiveRecordOID = $params['ActiveRecordOID']; $field = $params['field']; } catch (\Exception $e) { self::$logger->error('Required param missing for RecordSelectorController controller[' . $e->getMessage() . ']'); throw new ResourceNotFoundException('File not found'); } if ($relationType == 'MANY-TO-MANY') { try { $relatedClassLeft = urldecode($params['relatedClassLeft']); $relatedClassLeftDisplayField = $params['relatedClassLeftDisplayField']; $relatedClassRight = urldecode($params['relatedClassRight']); $relatedClassRightDisplayField = $params['relatedClassRightDisplayField']; $accessingClassName = urldecode($params['accessingClassName']); $lookupOIDs = $params['lookupOIDs']; } catch (\Exception $e) { self::$logger->error('Required param missing for RecordSelectorController controller[' . $e->getMessage() . ']'); throw new ResourceNotFoundException('File not found'); } $relationObject->setRelatedClass($relatedClassLeft, 'left'); $relationObject->setRelatedClassDisplayField($relatedClassLeftDisplayField, 'left'); $relationObject->setRelatedClass($relatedClassRight, 'right'); $relationObject->setRelatedClassDisplayField($relatedClassRightDisplayField, 'right'); $relationObject->setRelationType($relationType); $relationObject->setValue($ActiveRecordOID); $recSelector = new RecordSelector($relationObject, '', $field, $accessingClassName); $body .= $recSelector->renderSelector($field, explode(',', $lookupOIDs)); } else { try { $relatedClass = urldecode($params['relatedClass']); $relatedClassField = $params['relatedClassField']; $relatedClassDisplayField = $params['relatedClassDisplayField']; } catch (\Exception $e) { self::$logger->error('Required param missing for RecordSelectorController controller[' . $e->getMessage() . ']'); throw new ResourceNotFoundException('File not found'); } $relationObject->setRelatedClass($relatedClass); $relationObject->setRelatedClassField($relatedClassField); $relationObject->setRelatedClassDisplayField($relatedClassDisplayField); $relationObject->setRelationType($relationType); $relationObject->setValue($ActiveRecordOID); $recSelector = new RecordSelector($relationObject); $body .= $recSelector->renderSelector($field); } self::$logger->debug('<<__doGet'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * A static method that attempts to return a ActiveRecordProviderInterface instance * based on the name of the provider class supplied. * * @param $providerName The fully-qualified class name of the provider class. * @param $BO The (optional) active record instance to pass to the persistance provider for mapping. * * @throws Alpha\Exception\IllegalArguementException * * @return Alpha\Model\ActiveRecordProviderInterface * * @since 1.1 */ public static function getInstance($providerName, $BO = null) { if (self::$logger == null) { self::$logger = new Logger('ActiveRecordProviderFactory'); } self::$logger->debug('>>getInstance(providerName=[' . $providerName . '], BO=[' . print_r($BO, true) . '])'); $config = ConfigProvider::getInstance(); if (class_exists($providerName)) { $instance = new $providerName(); if (!$instance instanceof ActiveRecordProviderInterface) { throw new IllegalArguementException('The class [' . $providerName . '] does not implement the expected ActiveRecordProviderInterface interface!'); } if ($BO instanceof ActiveRecord) { $instance->setBO($BO); } self::$logger->debug('<<getInstance: [Object ' . $providerName . ']'); return $instance; } else { throw new IllegalArguementException('The class [' . $providerName . '] is not defined anywhere!'); } self::$logger->debug('<<getInstance'); }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 2.0.3 */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); if ($request->getParam('displayphpinfo') != null) { ob_start(); phpinfo(); $body = ob_get_contents(); } else { $body = View::displayPageHead($this); $url = FrontController::generateSecureURL('act=Alpha\\Controller\\PhpinfoController&displayphpinfo=true'); $body .= '<iframe src="' . $url . '" style="border:none; overflow-x: scroll; overflow-y: scroll; width:100%; height:100vh;"></iframe>'; $body .= View::displayPageFoot($this); } self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html', 'X-Frame-Options' => 'SAMEORIGIN')); }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $body = View::displayPageHead($this); if ($request->getParam('dir')) { $dir = $request->getParam('dir'); } else { $dir = $config->get('app.root'); } $metrics = new Inspector($dir); $metrics->calculateLOC(); $body .= $metrics->resultsToHTML(); $body .= View::displayPageFoot($this); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * (non-PHPdoc). * * @see Alpha\Model\ActiveRecordProviderInterface::rollback() */ public static function rollback() { if (self::$logger == null) { self::$logger = new Logger('ActiveRecordProviderSQLite'); } self::$logger->debug('>>rollback()'); try { self::getConnection()->exec('ROLLBACK'); self::disconnect(); } catch (Exception $e) { if (mb_strpos($e->getMessage(), 'cannot rollback - no transaction is active') === false) { // just filtering out errors where the rollback failed due to no current transaction throw new AlphaException('Error rolling back a transaction, error is [' . self::getLastDatabaseError() . ']'); } } self::$logger->debug('<<rollback'); }
/** * Handle POST requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doPOST($request) { self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $params = $request->getParams(); $body = View::displayPageHead($this); $body .= '<p class="alert alert-success">'; if (isset($params['QS'])) { $body .= FrontController::generateSecureURL($params['QS']); self::$logger->action('Generated the secure URL in admin: ' . FrontController::generateSecureURL($params['QS'])); } $body .= '</p>'; $body .= $this->renderForm(); $body .= View::displayPageFoot($this); self::$logger->debug('<<doPOST'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doGET($request) { self::$logger->debug('>>doGET(request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); if ($config->get('app.check.installed') && !ActiveRecord::isInstalled()) { $response = new Response(301); $response->redirect($config->get('app.url') . '/install'); self::$logger->warn('App not installed so re-directing to the install controller'); self::$logger->debug('<<doGET'); return $response; } $params = $request->getParams(); $body = View::loadTemplateFragment('html', 'head.phtml', array('title' => $config->get('app.title'), 'description' => 'Welcome to our site', 'allowCSSOverrides' => true)); $body .= View::loadTemplateFragment('html', 'index.phtml'); $body .= View::loadTemplateFragment('html', 'footer.phtml'); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $config = ConfigProvider::getInstance(); if ($this->record instanceof Person) { self::$logger->debug('Logging out [' . $this->record->get('email') . '] at [' . date('Y-m-d H:i:s') . ']'); self::$logger->action('Logout'); } $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); $session->destroy(); $body = View::displayPageHead($this); $body .= View::displayUpdateMessage('You have successfully logged out of the system.'); $body .= '<div align="center"><a href="' . $config->get('app.url') . '">Home Page</a></div>'; $body .= View::displayPageFoot($this); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Load the tag search matches from the cache. * * @since 1.2.4 */ private function loadFromCache($key) { $config = ConfigProvider::getInstance(); try { $cache = CacheProviderFactory::getInstance($config->get('cache.provider.name')); $matches = $cache->get($key); if (!$matches) { self::$logger->debug('Cache miss on key [' . $key . ']'); return array(); } else { self::$logger->debug('Cache hit on key [' . $key . ']'); return $matches; } } catch (\Exception $e) { self::$logger->error('Error while attempting to load a search result from [' . $config->get('cache.provider.name') . '] instance: [' . $e->getMessage() . ']'); return array(); } }
/** * Handle POST requests. * * @param Alpha\Util\Http\Response $request * * @throws Alpha\Exception\SecurityException * @throws Alpha\Exception\IllegalArguementException * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doPOST($request) { self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])'); $params = $request->getParams(); try { // check the hidden security fields before accepting the form POST data if (!$this->checkSecurityFields()) { throw new SecurityException('This page cannot accept post data from remote servers!'); } if (!is_array($params)) { throw new IllegalArguementException('Bad $params [' . var_export($params, true) . '] passed to doPOST method!'); } if (isset($params['clearCache']) && $params['clearCache'] == 'true') { try { FileUtils::deleteDirectoryContents($this->dataDir, array('.htaccess', 'html', 'images', 'pdf', 'xls')); $this->setStatusMessage(View::displayUpdateMessage('Cache contents deleted successfully.')); $config = ConfigProvider::getInstance(); $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); self::$logger->info('Cache contents deleted successfully by user [' . $session->get('currentUser')->get('displayName') . '].'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); } } return $this->doGET($request); } catch (SecurityException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); self::$logger->warn($e->getMessage()); } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); } $body = View::displayPageHead($this); $message = $this->getStatusMessage(); if (!empty($message)) { $body .= $message; } $body .= View::displayPageFoot($this); self::$logger->debug('<<doPOST'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Constructor. * * @param $limit The maximum amount of tags to include in the cloud. * @param $cacheKey Set this optional value to attempt to store the tag cloud array in the available cache for 24hrs (cache.provider.name). * * @since 1.0 */ public function __construct($limit, $cacheKey = '') { $config = ConfigProvider::getInstance(); self::$logger = new Logger('TagCloud'); if ($cacheKey != '' && $config->get('cache.provider.name') != '') { $cache = CacheProviderFactory::getInstance($config->get('cache.provider.name')); $this->popTags = $cache->get($cacheKey); // cache look-up failed, so add it for the next time if (!$this->popTags) { self::$logger->debug('Cache lookup on the key [' . $cacheKey . '] failed, regenerating popular tags...'); $this->popTags = Tag::getPopularTagsArray($limit); $cache->set($cacheKey, $this->popTags, 86400); } else { $this->popTags = array_slice($this->popTags, 0, $limit); self::$logger->debug('Cache lookup on the key [' . $cacheKey . '] succeeded'); } } else { $this->popTags = Tag::getPopularTagsArray($limit); } }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 * * @throws Alpha\Exception\IllegalArguementException */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); $params = $request->getParams(); if (isset($params['start']) ? $this->startPoint = $params['start'] : ($this->startPoint = 0)) { } $config = ConfigProvider::getInstance(); $KPI = new KPI('search'); $body = ''; if (isset($params['query'])) { $this->query = $params['query']; // replace any %20 on the URL with spaces $params['query'] = str_replace('%20', ' ', $params['query']); $this->setTitle('Search results - ' . $params['query']); $body .= View::displayPageHead($this); // log the user's search query in a log file $log = new LogProviderFile(); $log->setPath($config->get('app.file.store.dir') . 'logs/search.log'); $log->writeLine(array($params['query'], date('Y-m-d H:i:s'), $request->getUserAgent(), $request->getIP())); $KPI->logStep('log search query'); $provider = SearchProviderFactory::getInstance('Alpha\\Util\\Search\\SearchProviderTags'); // if a BO name is provided, only search tags on that class, otherwise search all BOs if (isset($params['ActiveRecordType'])) { $results = $provider->search($params['query'], $params['bo'], $this->startPoint); } else { $results = $provider->search($params['query'], 'all', $this->startPoint); } $this->resultCount = $provider->getNumberFound(); $KPI->logStep('search completed using SearchProviderTags provider'); $body .= $this->renderResultList($results, $params['query']); } else { $this->setTitle('Search results'); $body .= View::displayPageHead($this); self::$logger->debug('No search query provided!'); } $body .= View::displayPageFoot($this); $KPI->log(); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Returns the output as an Excel spreadsheet. * * @param bool $renderHeaders Set to false to supress headers in the spreadsheet (defaults to true). * * @return string * * @since 1.0 */ public function render($renderHeaders = true) { self::$logger->debug('>>render()'); //define separator (tabbed character) $sep = "\t"; $output = ''; // get the class attributes $reflection = new \ReflectionClass(get_class($this->BO)); $properties = $reflection->getProperties(); // print headers if ($renderHeaders) { $output .= $this->BO->getDataLabel('OID') . $sep; foreach ($properties as $propObj) { $propName = $propObj->name; if (!in_array($propName, $this->BO->getTransientAttributes()) && !in_array($propName, $this->BO->getDefaultAttributes())) { $output .= $this->BO->getDataLabel($propName) . $sep; } } $output .= "\n"; } // print values $output .= $this->BO->getOID() . $sep; foreach ($properties as $propObj) { $propName = $propObj->name; $prop = $this->BO->getPropObject($propName); if (!in_array($propName, $this->BO->getTransientAttributes()) && !in_array($propName, $this->BO->getDefaultAttributes())) { if (get_class($prop) == 'DEnum') { $output .= $prop->getDisplayValue() . $sep; } elseif (get_class($prop) == 'Relation') { $output .= $prop->getRelatedClassDisplayFieldValue() . $sep; } else { $output .= preg_replace("/[\n\r]/", '', $prop->getValue()) . $sep; } } } $output .= "\n"; self::$logger->debug('<<render'); return $output; }
/** * Custom version of the check rights method that only checks for a session for the config admin username/password, * when the system database is not set-up. * * @return bool * * @since 1.0 */ public function checkRights() { self::$logger->debug('>>checkRights()'); $config = ConfigProvider::getInstance(); $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); if ($this->getVisibility() == 'Public') { self::$logger->debug('<<checkRights [true]'); return true; } if (ActiveRecord::isInstalled()) { self::$logger->debug('<<checkRights [false]'); return false; } // the person is logged in? if ($session->get('currentUser') !== false) { if ($session->get('currentUser')->get('email') == $config->get('app.install.username')) { self::$logger->debug('<<checkRights [true]'); return true; } } }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\IllegalArguementException * * @since 1.0 */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $body = ''; try { // load the business object (BO) definition if (isset($params['logPath']) && file_exists(urldecode($params['logPath']))) { $logPath = urldecode($params['logPath']); } else { throw new IllegalArguementException('No log file available to view!'); } $this->logPath = $logPath; $body .= View::displayPageHead($this); $log = new LogProviderFile(); $log->setPath($this->logPath); if (preg_match('/alpha.*/', basename($this->logPath))) { $body .= $log->renderLog(array('Date/time', 'Level', 'Class', 'Message', 'Client', 'IP', 'Server hostname', 'URI')); } if (preg_match('/search.*/', basename($this->logPath))) { $body .= $log->renderLog(array('Search query', 'Search date', 'Client Application', 'Client IP')); } if (preg_match('/feeds.*/', basename($this->logPath))) { $body .= $log->renderLog(array('Business object', 'Feed type', 'Request date', 'Client Application', 'Client IP')); } if (preg_match('/tasks.*/', basename($this->logPath))) { $body .= $log->renderLog(array('Date/time', 'Level', 'Class', 'Message')); } $body .= View::displayPageFoot($this); } catch (IllegalArguementException $e) { self::$logger->warn($e->getMessage()); $body .= View::displayPageHead($this); $body .= View::displayErrorMessage($e->getMessage()); $body .= View::displayPageFoot($this); } self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Loads a template fragment from the Renderer/[type]/Fragments/[filename.ext] location. * * @param string $type Currently only html supported, later json and xml. * @param string $fileName The name of the fragment file * @param array $fields A hash array of field values to pass to the template fragment. * * @return string * * @since 1.2 * * @throws Alpha\Exception\IllegalArguementException */ public static function loadTemplateFragment($type, $fileName, $fields = array()) { if (self::$logger == null) { self::$logger = new Logger('View'); } self::$logger->debug('>>loadTemplateFragment(type=[' . $type . '], fileName=[' . $fileName . '], fields=[' . var_export($fields, true) . '])'); $config = ConfigProvider::getInstance(); // loop over the $fields array and create a local variable for each key value foreach (array_keys($fields) as $fieldName) { ${$fieldName} = $fields[$fieldName]; } $customPath = $config->get('app.root') . 'src/View/' . ucfirst($type) . '/Fragments/' . $fileName; $defaultPath1 = $config->get('app.root') . 'vendor/alphadevx/alpha/Alpha/View/Renderer/' . ucfirst($type) . '/Fragments/' . $fileName; $defaultPath2 = $config->get('app.root') . 'Alpha/View/Renderer/' . ucfirst($type) . '/Fragments/' . $fileName; // Check to see if a custom template exists for this BO, and if it does load that if (file_exists($customPath)) { self::$logger->debug('Loading template [' . $customPath . ']'); ob_start(); require $customPath; $html = ob_get_clean(); return $html; } elseif (file_exists($defaultPath1)) { self::$logger->debug('Loading template [' . $defaultPath1 . ']'); ob_start(); require $defaultPath1; $html = ob_get_clean(); return $html; } elseif (file_exists($defaultPath2)) { self::$logger->debug('Loading template [' . $defaultPath2 . ']'); ob_start(); require $defaultPath2; $html = ob_get_clean(); return $html; } else { throw new IllegalArguementException('Template fragment not found in [' . $customPath . '] or [' . $defaultPath1 . '] or [' . $defaultPath2 . ']!'); } self::$logger->debug('<<loadTemplateFragment'); }
/** * Custom display view. * * @param array $fields Hash array of HTML fields to pass to the template. * * @since 1.0 */ public function detailedView($fields = array()) { self::$logger->debug('>>detailedView(fields=[' . var_export($fields, true) . '])'); if (method_exists($this, 'before_detailedView_callback')) { $this->before_detailedView_callback(); } $config = ConfigProvider::getInstance(); // we may want to display the OID regardless of class $fields['OIDLabel'] = $this->BO->getDataLabel('OID'); $fields['OID'] = $this->BO->getOID(); // buffer form fields to $formFields $fields['formFields'] = $this->renderAllFields('view'); // Back button $button = new Button('history.back()', 'Back', 'backBut'); $fields['backButton'] = $button->render(); $fields['adminButtons'] = ''; $html = $this->loadTemplate($this->BO, 'detail', $fields); if (method_exists($this, 'after_detailedView_callback')) { $this->after_detailedView_callback(); } self::$logger->debug('<<detailedView'); return $html; }
/** * Handle GET requests. * * @param Alpha\Util\Http\Request $request * * @since 1.0 * * @throws Alpha\Exception\ResourceNotFoundException */ public function doGET($request) { self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $params = $request->getParams(); try { if (isset($params['articleOID']) && isset($params['filename'])) { if (!Validator::isInteger($params['articleOID'])) { throw new IllegalArguementException('The articleOID [' . $params['articleOID'] . '] provided is invalid'); } $article = new Article(); $article->setOID($params['articleOID']); $filePath = $article->getAttachmentsLocation() . '/' . $params['filename']; if (file_exists($filePath)) { self::$logger->info('Downloading the file [' . $params['filename'] . '] from the folder [' . $article->getAttachmentsLocation() . ']'); $pathParts = pathinfo($filePath); $mimeType = FileUtils::getMIMETypeByExtension($pathParts['extension']); $response = new Response(200, file_get_contents($filePath)); $response->setHeader('Content-Type', $mimeType); $response->setHeader('Content-Disposition', 'attachment; filename="' . $pathParts['basename'] . '"'); $response->setHeader('Content-Length', filesize($filePath)); self::$logger->debug('<<doGET'); return $response; } else { self::$logger->error('Could not access article attachment file [' . $filePath . '] as it does not exist!'); throw new IllegalArguementException('File not found'); } } else { self::$logger->error('Could not access article attachment as articleOID and/or filename were not provided!'); throw new IllegalArguementException('File not found'); } } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException($e->getMessage()); } self::$logger->debug('<<doGET'); }
/** * Handle POST requests. * * @param alpha\Util\Http\Request $request * * @return alpha\Util\Http\Response * * @since 1.0 */ public function doPOST($request) { self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $config = ConfigProvider::getInstance(); $body = View::displayPageHead($this); try { // check the hidden security fields before accepting the form POST data if (!$this->checkSecurityFields()) { throw new SecurityException('This page cannot accept post data from remote servers!'); } if (isset($params['createTableBut'])) { try { $classname = $params['createTableClass']; $BO = new $classname(); $BO->makeTable(); self::$logger->action('Created the table for class ' . $classname); $body .= View::displayUpdateMessage('The table for the class ' . $classname . ' has been successfully created.'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); $body .= View::displayErrorMessage('Error creating the table for the class ' . $classname . ', check the log!'); } } if (isset($params['createHistoryTableBut'])) { try { $classname = $params['createTableClass']; $BO = new $classname(); $BO->makeHistoryTable(); self::$logger->action('Created the history table for class ' . $classname); $body .= View::displayUpdateMessage('The history table for the class ' . $classname . ' has been successfully created.'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); $body .= View::displayErrorMessage('Error creating the history table for the class ' . $classname . ', check the log!'); } } if (isset($params['recreateTableClass']) && $params['admin_' . stripslashes($params['recreateTableClass']) . '_button_pressed'] == 'recreateTableBut') { try { $classname = $params['recreateTableClass']; $BO = new $classname(); $BO->rebuildTable(); self::$logger->action('Recreated the table for class ' . $classname); $body .= View::displayUpdateMessage('The table for the class ' . $classname . ' has been successfully recreated.'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); $body .= View::displayErrorMessage('Error recreating the table for the class ' . $classname . ', check the log!'); } } if (isset($params['updateTableClass']) && $params['admin_' . stripslashes($params['updateTableClass']) . '_button_pressed'] == 'updateTableBut') { try { $classname = $params['updateTableClass']; $BO = new $classname(); $missingFields = $BO->findMissingFields(); $count = count($missingFields); for ($i = 0; $i < $count; ++$i) { $BO->addProperty($missingFields[$i]); } self::$logger->action('Updated the table for class ' . $classname); $body .= View::displayUpdateMessage('The table for the class ' . $classname . ' has been successfully updated.'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); $body .= View::displayErrorMessage('Error updating the table for the class ' . $classname . ', check the log!'); } } } catch (SecurityException $e) { $body .= View::displayErrorMessage($e->getMessage()); self::$logger->warn($e->getMessage()); } $body .= $this->displayBodyContent(); $body .= View::displayPageFoot($this); self::$logger->debug('<<doPOST'); return new Response(200, $body, array('Content-Type' => 'text/html')); }