/** * 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; } }
/** * Private method to generate the main body HTML for this page. * * @since 1.0 * * @return string */ private function displayBodyContent() { $classNames = ActiveRecord::getBOClassNames(); $body = ''; $fields = array('formAction' => $this->request->getURI()); foreach ($classNames as $className) { try { $activeRecord = new $className(); $view = View::getInstance($activeRecord); $body .= $view->adminView($fields); } catch (AlphaException $e) { self::$logger->error("[{$classname}]:" . $e->getMessage()); // its possible that the exception occured due to the table schema being out of date if ($activeRecord->checkTableExists() && $activeRecord->checkTableNeedsUpdate()) { $missingFields = $activeRecord->findMissingFields(); $count = count($missingFields); for ($i = 0; $i < $count; ++$i) { $activeRecord->addProperty($missingFields[$i]); } // now try again... $activeRecord = new $className(); $view = View::getInstance($activeRecord); $body .= $view->adminView($fields); } } catch (\Exception $e) { self::$logger->error($e->getMessage()); $body .= View::displayErrorMessage('Error accessing the class [' . $classname . '], check the log!'); } } return $body; }
/** * {@inheritdoc} */ public function delete($key) { try { $this->connection->delete($key); } catch (\Exception $e) { self::$logger->error('Error while attempting to remove a value from Memcached instance: [' . $e->getMessage() . ']'); } }
/** * {@inheritdoc} */ public function delete($key) { try { apc_delete($key); } catch (\Exception $e) { self::$logger->error('Error while attempting to remove a value from APC cache: [' . $e->getMessage() . ']'); } }
/** * 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')); }
/** * Add the tag search matches to the cache. * * @since 1.2.4 */ public function addToCache($key, $matches) { $config = ConfigProvider::getInstance(); try { $cache = CacheProviderFactory::getInstance($config->get('cache.provider.name')); $cache->set($key, $matches, 86400); // cache search matches for a day } catch (\Exception $e) { self::$logger->error('Error while attempting to store a search matches array to the [' . $config->get('cache.provider.name') . '] instance: [' . $e->getMessage() . ']'); } }
/** * 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')); }
/** * 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'); }
/** * Method to create the DEnum tables if they don't exist. * * @since 1.0 * * @return string */ private function createDEnumTables() { $tmpDEnum = new DEnum(); $body = '<p>Attempting to build table ' . DEnum::TABLE_NAME . ' for class DEnum : </p>'; try { $tmpDEnum->makeTable(); $body .= View::displayUpdateMessage('Successfully re-created the database table ' . DEnum::TABLE_NAME); self::$logger->action('Re-created the table ' . DEnum::TABLE_NAME); } catch (AlphaException $e) { $body .= View::displayErrorMessage('Failed re-created the database table ' . DEnum::TABLE_NAME . ', check the log'); self::$logger->error($e->getMessage()); } $tmpDEnumItem = new DEnumItem(); $body .= '<p>Attempting to build table ' . DEnumItem::TABLE_NAME . ' for class DEnumItem : </p>'; try { $tmpDEnumItem->makeTable(); $body .= View::displayUpdateMessage('Successfully re-created the database table ' . DEnumItem::TABLE_NAME); self::$logger->action('Re-created the table ' . DEnumItem::TABLE_NAME); } catch (AlphaException $e) { $body .= View::displayErrorMessage('Failed re-created the database table ' . DEnumItem::TABLE_NAME . ', check the log'); self::$logger->error($e->getMessage()); } return $body; }
/** * Commits (saves) all of the new and modified (dirty) objects in the unit of work to the database. * * @throws FailedUnitCommitException * * @since 1.0 */ public function commit() { self::$logger->debug('>>commit()'); if (method_exists($this, 'before_commit_callback')) { $this->before_commit_callback(); } ActiveRecord::begin(); $newObjects = $this->getNewObjects(); $count = count($newObjects); for ($i = 0; $i < $count; ++$i) { try { $newObjects[$i]->save(); } catch (FailedSaveException $e) { throw new FailedUnitCommitException($e->getMessage()); self::$logger->error('Failed to save new object of type [' . get_class($newObjects[$i]) . '], aborting...'); $this->abort(); return; } catch (LockingException $e) { throw new FailedUnitCommitException($e->getMessage()); self::$logger->error('Failed to save new object of type [' . get_class($newObjects[$i]) . '], aborting...'); $this->abort(); return; } } $dirtyObjects = $this->getDirtyObjects(); $count = count($dirtyObjects); for ($i = 0; $i < $count; ++$i) { try { $dirtyObjects[$i]->save(); } catch (FailedSaveException $e) { throw new FailedUnitCommitException($e->getMessage()); self::$logger->error('Failed to save OID [' . $dirtyObjects[$i]->getID() . '] of type [' . get_class($dirtyObjects[$i]) . '], aborting...'); $this->abort(); return; } catch (LockingException $e) { throw new FailedUnitCommitException($e->getMessage()); self::$logger->error('Failed to save OID [' . $dirtyObjects[$i]->getID() . '] of type [' . get_class($dirtyObjects[$i]) . '], aborting...'); $this->abort(); return; } } try { ActiveRecord::commit(); $this->clearUnitOfWorkAttributes(); if (method_exists($this, 'after_commit_callback')) { $this->after_commit_callback(); } self::$logger->debug('<<commit'); } catch (FailedSaveException $e) { throw new FailedUnitCommitException('Failed to commit the transaction, error is [' . $e->getMessage() . ']'); self::$logger->debug('<<commit'); } }
/** * Handle POST requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\SecurityException * @throws Alpha\Exception\IllegalArguementException * * @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 (isset($params['clearTaggedClass']) && $params['clearTaggedClass'] != '') { try { self::$logger->info('About to start rebuilding the tags for the class [' . $params['clearTaggedClass'] . ']'); $startTime = microtime(true); $record = new $params['clearTaggedClass'](); $records = $record->loadAll(); self::$logger->info('Loaded all of the active records (elapsed time [' . round(microtime(true) - $startTime, 5) . '] seconds)'); ActiveRecord::begin(); $tag = new Tag(); $tag->deleteAllByAttribute('taggedClass', $params['clearTaggedClass']); self::$logger->info('Deleted all of the old tags (elapsed time [' . round(microtime(true) - $startTime, 5) . '] seconds)'); $this->regenerateTagsOnRecords($records); self::$logger->info('Saved all of the new tags (elapsed time [' . round(microtime(true) - $startTime, 5) . '] seconds)'); self::$logger->action('Tags recreated on the [' . $params['clearTaggedClass'] . '] class'); ActiveRecord::commit(); $this->setStatusMessage(View::displayUpdateMessage('Tags recreated on the ' . $record->getFriendlyClassName() . ' class.')); self::$logger->info('Tags recreated on the [' . $params['clearTaggedClass'] . '] class (time taken [' . round(microtime(true) - $startTime, 5) . '] seconds).'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); ActiveRecord::rollback(); } ActiveRecord::disconnect(); return $this->doGET($request); } elseif (isset($params['ActiveRecordType']) && isset($params['ActiveRecordOID'])) { $ActiveRecordType = urldecode($params['ActiveRecordType']); $ActiveRecordOID = $params['ActiveRecordOID']; if (class_exists($ActiveRecordType)) { $record = new $ActiveRecordType(); } else { throw new IllegalArguementException('No ActiveRecord available to display tags for!'); } if (isset($params['saveBut'])) { try { $record->load($ActiveRecordOID); $tags = $record->getPropObject('tags')->getRelatedObjects(); ActiveRecord::begin(); foreach ($tags as $tag) { $tag->set('content', Tag::cleanTagContent($params['content_' . $tag->getID()])); $tag->save(); self::$logger->action('Saved tag ' . $tag->get('content') . ' on ' . $ActiveRecordType . ' instance with OID ' . $ActiveRecordOID); } // handle new tag if posted if (isset($params['NewTagValue']) && trim($params['NewTagValue']) != '') { $newTag = new Tag(); $newTag->set('content', Tag::cleanTagContent($params['NewTagValue'])); $newTag->set('taggedOID', $ActiveRecordOID); $newTag->set('taggedClass', $ActiveRecordType); $newTag->save(); self::$logger->action('Created a new tag ' . $newTag->get('content') . ' on ' . $ActiveRecordType . ' instance with OID ' . $ActiveRecordOID); } ActiveRecord::commit(); $this->setStatusMessage(View::displayUpdateMessage('Tags on ' . get_class($record) . ' ' . $record->getID() . ' saved successfully.')); return $this->doGET($request); } catch (ValidationException $e) { /* * The unique key has most-likely been violated because this BO is already tagged with this * value. */ ActiveRecord::rollback(); $this->setStatusMessage(View::displayErrorMessage('Tags on ' . get_class($record) . ' ' . $record->getID() . ' not saved due to duplicate tag values, please try again.')); return $this->doGET($request); } catch (FailedSaveException $e) { self::$logger->error('Unable to save the tags of id [' . $params['ActiveRecordOID'] . '], error was [' . $e->getMessage() . ']'); ActiveRecord::rollback(); $this->setStatusMessage(View::displayErrorMessage('Tags on ' . get_class($record) . ' ' . $record->getID() . ' not saved, please check the application logs.')); return $this->doGET($request); } ActiveRecord::disconnect(); } } else { return parent::doPOST($request); } } catch (SecurityException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); self::$logger->warn($e->getMessage()); } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); } catch (RecordNotFoundException $e) { self::$logger->warn($e->getMessage()); $this->setStatusMessage(View::displayErrorMessage('Failed to load the requested item from the database!')); } self::$logger->debug('<<doPOST'); }
/** * Loads the BO indicated in the GET request and handles the conversion to Excel. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\ResourceNotFoundException * * @since 1.0 */ public function doGet($request) { self::$logger->debug('>>doGet(request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $body = ''; try { if (isset($params['ActiveRecordType'])) { $ActiveRecordType = $params['ActiveRecordType']; $className = "Alpha\\Model\\{$ActiveRecordType}"; if (class_exists($className)) { $this->BO = new $className(); } else { throw new IllegalArguementException('No ActiveRecord available to render!'); } // the name of the file download if (isset($params['ActiveRecordOID'])) { $fileName = $this->BO->getTableName() . '-' . $params['ActiveRecordOID']; } else { $fileName = $this->BO->getTableName(); } $response = new Response(200); // header info for browser $response->setHeader('Content-Type', 'application/vnd.ms-excel'); $response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName . '.xls'); $response->setHeader('Pragma', 'no-cache'); $response->setHeader('Expires', '0'); // handle a single BO if (isset($params['ActiveRecordOID'])) { $this->BO->load($params['ActiveRecordOID']); ActiveRecord::disconnect(); $convertor = new ActiveRecord2Excel($this->BO); $body .= $convertor->render(); } else { // handle all BOs of this type $BOs = $BO->loadAll(); ActiveRecord::disconnect(); $first = true; foreach ($BOs as $BO) { $convertor = new ActiveRecord2Excel($BO); if ($first) { $body .= $convertor->render(true); $first = false; } else { $body .= $convertor->render(false); } } } } else { throw new IllegalArguementException('No ActiveRecordType parameter available for ViewExcel controller!'); } } catch (RecordNotFoundException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException($e->getMessage()); } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException($e->getMessage()); } self::$logger->debug('<<__doGet'); $response->setBody($body); return $response; }
/** * 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(); $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); // if there is nobody logged in, we will send them off to the Login controller to do so before coming back here if ($session->get('currentUser') === false) { self::$logger->info('Nobody logged in, invoking Login controller...'); $controller = new LoginController(); $controller->setName('LoginController'); $controller->setRequest($request); $controller->setUnitOfWork(array('Alpha\\Controller\\LoginController', 'Alpha\\Controller\\InstallController')); self::$logger->debug('<<__construct'); return $controller->doGET($request); } $params = $request->getParams(); $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); $body = View::displayPageHead($this); $body .= '<h1>Installing the ' . $config->get('app.title') . ' application</h1>'; try { $body .= $this->createApplicationDirs(); } catch (\Exception $e) { $body .= View::displayErrorMessage($e->getMessage()); $body .= View::displayErrorMessage('Aborting.'); return new Response(500, $body, array('Content-Type' => 'text/html')); } // start a new database transaction ActiveRecord::begin(); /* * Create DEnum tables */ $DEnum = new DEnum(); $DEnumItem = new DEnumItem(); try { $body .= '<p>Attempting to create the DEnum tables...'; if (!$DEnum->checkTableExists()) { $DEnum->makeTable(); } self::$logger->info('Created the [' . $DEnum->getTableName() . '] table successfully'); if (!$DEnumItem->checkTableExists()) { $DEnumItem->makeTable(); } self::$logger->info('Created the [' . $DEnumItem->getTableName() . '] table successfully'); // create a default article DEnum category $DEnum = new DEnum('Alpha\\Model\\Article::section'); $DEnumItem = new DEnumItem(); $DEnumItem->set('value', 'Main'); $DEnumItem->set('DEnumID', $DEnum->getID()); $DEnumItem->save(); $body .= View::displayUpdateMessage('DEnums set up successfully.'); } catch (\Exception $e) { $body .= View::displayErrorMessage($e->getMessage()); $body .= View::displayErrorMessage('Aborting.'); self::$logger->error($e->getMessage()); ActiveRecord::rollback(); return new Response(500, $body, array('Content-Type' => 'text/html')); } /* * Loop over each business object in the system, and create a table for it */ $classNames = ActiveRecord::getBOClassNames(); $loadedClasses = array(); foreach ($classNames as $classname) { array_push($loadedClasses, $classname); } foreach ($loadedClasses as $classname) { try { $body .= '<p>Attempting to create the table for the class [' . $classname . ']...'; try { $BO = new $classname(); if (!$BO->checkTableExists()) { $BO->makeTable(); } else { if ($BO->checkTableNeedsUpdate()) { $missingFields = $BO->findMissingFields(); $count = count($missingFields); for ($i = 0; $i < $count; ++$i) { $BO->addProperty($missingFields[$i]); } } } } catch (FailedIndexCreateException $eice) { // this are safe to ignore for now as they will be auto-created later once all of the tables are in place self::$logger->warn($eice->getMessage()); } catch (FailedLookupCreateException $elce) { // this are safe to ignore for now as they will be auto-created later once all of the tables are in place self::$logger->warn($elce->getMessage()); } self::$logger->info('Created the [' . $BO->getTableName() . '] table successfully'); $body .= View::displayUpdateMessage('Created the [' . $BO->getTableName() . '] table successfully'); } catch (\Exception $e) { $body .= View::displayErrorMessage($e->getMessage()); $body .= View::displayErrorMessage('Aborting.'); self::$logger->error($e->getMessage()); ActiveRecord::rollback(); return new Response(500, $body, array('Content-Type' => 'text/html')); } } $body .= View::displayUpdateMessage('All business object tables created successfully!'); /* * Create the Admin and Standard groups */ $adminGroup = new Rights(); $adminGroup->set('name', 'Admin'); $standardGroup = new Rights(); $standardGroup->set('name', 'Standard'); try { try { $body .= '<p>Attempting to create the Admin and Standard groups...'; $adminGroup->save(); $standardGroup->save(); self::$logger->info('Created the Admin and Standard rights groups successfully'); $body .= View::displayUpdateMessage('Created the Admin and Standard rights groups successfully'); } catch (FailedIndexCreateException $eice) { // this are safe to ignore for now as they will be auto-created later once all of the tables are in place self::$logger->warn($eice->getMessage()); } catch (FailedLookupCreateException $elce) { // this are safe to ignore for now as they will be auto-created later once all of the tables are in place self::$logger->warn($elce->getMessage()); } } catch (\Exception $e) { $body .= View::displayErrorMessage($e->getMessage()); $body .= View::displayErrorMessage('Aborting.'); self::$logger->error($e->getMessage()); ActiveRecord::rollback(); return new Response(500, $body, array('Content-Type' => 'text/html')); } /* * Save the admin user to the database in the right group */ try { try { $body .= '<p>Attempting to save the Admin account...'; $admin = new Person(); $admin->set('displayName', 'Admin'); $admin->set('email', $session->get('currentUser')->get('email')); $admin->set('password', $session->get('currentUser')->get('password')); $admin->save(); self::$logger->info('Created the admin user account [' . $session->get('currentUser')->get('email') . '] successfully'); $adminGroup->loadByAttribute('name', 'Admin'); $lookup = $adminGroup->getMembers()->getLookup(); $lookup->setValue(array($admin->getID(), $adminGroup->getID())); $lookup->save(); self::$logger->info('Added the admin account to the Admin group successfully'); $body .= View::displayUpdateMessage('Added the admin account to the Admin group successfully'); } catch (FailedIndexCreateException $eice) { // this are safe to ignore for now as they will be auto-created later once all of the tables are in place self::$logger->warn($eice->getMessage()); } catch (FailedLookupCreateException $elce) { // this are safe to ignore for now as they will be auto-created later once all of the tables are in place self::$logger->warn($elce->getMessage()); } } catch (\Exception $e) { $body .= View::displayErrorMessage($e->getMessage()); $body .= View::displayErrorMessage('Aborting.'); self::$logger->error($e->getMessage()); ActiveRecord::rollback(); return new Response(500, $body, array('Content-Type' => 'text/html')); } $body .= '<br><p align="center"><a href="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ListActiveRecordsController') . '">Administration Home Page</a></p><br>'; $body .= View::displayPageFoot($this); // commit ActiveRecord::commit(); self::$logger->info('Finished installation!'); self::$logger->action('Installed the application'); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => 'text/html')); }
/** * Processes the supplied request by invoking the callable defined matching the request's URI. * * @param Alpha\Util\Http\Request $request The request to process * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\ResourceNotFoundException * @throws Alpha\Exception\ResourceNotAllowedException * @throws Alpha\Exception\AlphaException * * @since 2.0 */ public function process($request) { foreach ($this->filters as $filter) { $filter->process($request); } try { $callback = $this->getRouteCallback($request->getURI()); } catch (IllegalArguementException $e) { self::$logger->warn($e->getMessage()); throw new ResourceNotFoundException('Resource not found'); } if ($request->getURI() != $this->currentRoute) { if (isset($this->defaultParamValues[$this->currentRoute])) { $request->parseParamsFromRoute($this->currentRoute, $this->defaultParamValues[$this->currentRoute]); } else { $request->parseParamsFromRoute($this->currentRoute); } } try { $response = call_user_func($callback, $request); } catch (ResourceNotFoundException $rnfe) { self::$logger->info('ResourceNotFoundException throw, source message [' . $rnfe->getMessage() . ']'); return new Response(404, $rnfe->getMessage()); } if ($response instanceof Response) { return $response; } else { self::$logger->error('The callable defined for route [' . $request->getURI() . '] does not return a Response object'); throw new AlphaException('Unable to process request'); } }
/** * Attempts to load the business object from the configured cache instance. * * @since 1.1 * * @return bool */ public function loadFromCache() { self::$logger->debug('>>loadFromCache()'); $config = ConfigProvider::getInstance(); try { $cache = CacheProviderFactory::getInstance($config->get('cache.provider.name')); $BO = $cache->get(get_class($this) . '-' . $this->getOID()); if (!$BO) { self::$logger->debug('Cache miss on key [' . get_class($this) . '-' . $this->getOID() . ']'); self::$logger->debug('<<loadFromCache: [false]'); return false; } else { // get the class attributes $reflection = new ReflectionClass(get_class($this)); $properties = $reflection->getProperties(); foreach ($properties as $propObj) { $propName = $propObj->name; // filter transient attributes if (!in_array($propName, $this->transientAttributes)) { $this->set($propName, $BO->get($propName, true)); } elseif (!$propObj->isPrivate() && isset($this->{$propName}) && $this->{$propName} instanceof Relation) { $prop = $this->getPropObject($propName); // handle the setting of ONE-TO-MANY relation values if ($prop->getRelationType() == 'ONE-TO-MANY') { $this->set($propObj->name, $this->getOID()); } } } self::$logger->debug('<<loadFromCache: [true]'); return true; } } catch (Exception $e) { self::$logger->error('Error while attempting to load a business object from [' . $config->get('cache.provider.name') . '] instance: [' . $e->getMessage() . ']'); self::$logger->debug('<<loadFromCache: [false]'); return false; } }
/** * Method to handle DELETE requests. * * @param Alpha\Util\Http\Request $request * * @throws Alpha\Exception\IllegalArguementException * @throws Alpha\Exception\SecurityException * * @return Alpha\Util\Http\Response * * @since 2.0 */ public function doDELETE($request) { self::$logger->debug('>>doDELETE(request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $params = $request->getParams(); $accept = $request->getAccept(); try { // check the hidden security fields before accepting the form data if (!$this->checkSecurityFields()) { throw new SecurityException('This page cannot accept data from remote servers!'); } if (isset($params['ActiveRecordType'])) { $ActiveRecordType = urldecode($params['ActiveRecordType']); } else { throw new IllegalArguementException('No ActiveRecord available to edit!'); } if (class_exists($ActiveRecordType)) { $record = new $ActiveRecordType(); } else { throw new IllegalArguementException('No ActiveRecord [' . $ActiveRecordType . '] available to edit!'); } // 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!'); } $record->load($params['ActiveRecordOID']); ActiveRecord::begin(); $record->delete(); ActiveRecord::commit(); ActiveRecord::disconnect(); self::$logger->action('Deleted ' . $ActiveRecordType . ' instance with OID ' . $params['ActiveRecordOID']); if ($accept == 'application/json') { $response = new Response(200); $response->setHeader('Content-Type', 'application/json'); $response->setBody(json_encode(array('message' => 'deleted'))); } else { $response = new Response(301); if (isset($params['statusMessage'])) { $this->setStatusMessage(View::displayUpdateMessage($params['statusMessage'])); } else { $this->setStatusMessage(View::displayUpdateMessage('Deleted')); } if ($this->getNextJob() != '') { $response->redirect($this->getNextJob()); } else { if ($this->request->isSecureURI()) { $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . $ActiveRecordType . '&start=0&limit=' . $config->get('app.list.page.amount'))); } else { $response->redirect($config->get('app.url') . '/records/' . $params['ActiveRecordType']); } } } } catch (SecurityException $e) { self::$logger->warn($e->getMessage()); throw new ResourceNotAllowedException($e->getMessage()); } catch (RecordNotFoundException $e) { self::$logger->warn($e->getMessage()); throw new ResourceNotFoundException('The item that you have requested cannot be found!'); } catch (AlphaException $e) { self::$logger->error($e->getMessage()); ActiveRecord::rollback(); } self::$logger->debug('<<doDELETE'); return $response; }
/** * Handles get requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @since 1.0 * * @throws Alpha\Exception\ResourceNotFoundException * @throws Alpha\Exception\ResourceNotAllowedException */ public function doGet($request) { self::$logger->debug('>>doGet(request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $params = $request->getParams(); try { $imgSource = urldecode($params['source']); $imgWidth = $params['width']; $imgHeight = $params['height']; $imgType = $params['type']; $imgQuality = (double) $params['quality']; $imgScale = new Boolean($params['scale']); $imgSecure = new Boolean($params['secure']); } catch (\Exception $e) { self::$logger->error('Required param missing for ImageController controller[' . $e->getMessage() . ']'); throw new ResourceNotFoundException('File not found'); } $modified = filemtime($imgSource); $responseHeaders = array(); $responseHeaders['Last-Modified'] = date('D, d M Y H:i:s', $modified) . ' GMT'; $responseHeaders['Cache-Control'] = 'max-age=1800'; // exit if not modified if ($request->getHeader('If-Modified-Since') != null) { if (strtotime($request->getHeader('If-Modified-Since')) == $modified) { return new Response(304, '', $responseHeaders); } } // handle secure tokens if ($imgSecure->getBooleanValue() && $config->get('cms.images.widget.secure')) { $valid = $this->checkSecurityFields(); // if not valid, just return a blank black image of the same dimensions if (!$valid) { $im = imagecreatetruecolor($imgWidth, $imgHeight); $bgc = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, $imgWidth, $imgHeight, $bgc); if ($imgSource == 'png' && $config->get('cms.images.perserve.png')) { ob_start(); imagepng($im); $body = ob_get_contents(); $contentType = 'image/png'; ob_end_clean(); } else { ob_start(); imagejpeg($im); $body = ob_get_contents(); $contentType = 'image/jpeg'; ob_end_clean(); } imagedestroy($im); self::$logger->warn('The client [' . $request->getUserAgent() . '] was blocked from accessing the file [' . $imgSource . '] due to bad security tokens being provided'); $responseHeaders['Content-Type'] = $contentType; return new Response(200, $body, $responseHeaders); } } try { $image = new Image($imgSource, $imgWidth, $imgHeight, $imgType, $imgQuality, $imgScale->getBooleanValue(), $imgSecure->getBooleanValue()); ob_start(); $image->renderImage(); $body = ob_get_contents(); ob_end_clean(); } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException('File not found'); } self::$logger->debug('<<__doGet'); if ($imgSource == 'png' && $config->get('cms.images.perserve.png')) { $responseHeaders['Content-Type'] = 'image/png'; } else { $responseHeaders['Content-Type'] = 'image/jpeg'; } return new Response(200, $body, $responseHeaders); }
/** * Remove the tag search matches from the cache. * * @since 1.2.4 */ protected function after_save_callback() { $config = ConfigProvider::getInstance(); if ($config->get('cache.provider.name') != '') { try { $cache = CacheProviderFactory::getInstance($config->get('cache.provider.name')); $cache->delete($this->get('content')); } catch (\Exception $e) { self::$logger->error('Error while attempting to remove search matches array from the [' . $config->get('cache.provider.name') . '] instance: [' . $e->getMessage() . ']'); } } }
/** * Handle 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) . '])'); $config = ConfigProvider::getInstance(); $params = $request->getParams(); $response = new Response(200); try { if (isset($params['ActiveRecordType'])) { $ActiveRecordType = urldecode($params['ActiveRecordType']); } else { throw new IllegalArguementException('ActiveRecordType not specified to generate feed!'); } if (isset($params['type'])) { $type = $params['type']; } else { throw new IllegalArguementException('No feed type specified to generate feed!'); } if (class_exists($ActiveRecordType)) { $this->ActiveRecordType = $ActiveRecordType; } else { throw new IllegalArguementException('No ActiveRecord available to render!'); } $this->type = $type; $this->setup(); switch ($type) { case 'RSS2': $feed = new RSS2($this->ActiveRecordType, $this->title, str_replace('&', '&', $request->getURI()), $this->description); $feed->setFieldMappings($this->fieldMappings[0], $this->fieldMappings[1], $this->fieldMappings[2], $this->fieldMappings[3]); $response->setHeader('Content-Type', 'application/rss+xml'); break; case 'RSS': $feed = new RSS($this->ActiveRecordType, $this->title, str_replace('&', '&', $request->getURI()), $this->description); $feed->setFieldMappings($this->fieldMappings[0], $this->fieldMappings[1], $this->fieldMappings[2], $this->fieldMappings[3]); $response->setHeader('Content-Type', 'application/rss+xml'); break; case 'Atom': $feed = new Atom($this->ActiveRecordType, $this->title, str_replace('&', '&', $request->getURI()), $this->description); $feed->setFieldMappings($this->fieldMappings[0], $this->fieldMappings[1], $this->fieldMappings[2], $this->fieldMappings[3], $this->fieldMappings[4]); if ($config->get('feeds.atom.author') != '') { $feed->addAuthor($config->get('feeds.atom.author')); } $response->setHeader('Content-Type', 'application/atom+xml'); break; } // now add the twenty last items (from newest to oldest) to the feed, and render $feed->loadBOs(20, $this->sortBy); $response->setBody($feed->render()); // log the request for this news feed $feedLog = new LogProviderFile(); $feedLog->setPath($config->get('app.file.store.dir') . 'logs/feeds.log'); $feedLog->writeLine(array($this->ActiveRecordType, $this->type, date('Y-m-d H:i:s'), $request->getUserAgent(), $request->getIP())); } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException($e->getMessage()); } self::$logger->debug('<<doGet'); return $response; }
/** * Checks to see if all of the indexes are in place for the BO's table, creates those that are missing. * * @since 1.1 */ private function checkIndexes() { self::$logger->debug('>>checkIndexes()'); $indexNames = $this->getIndexes(); // process unique keys foreach ($this->BO->getUniqueAttributes() as $prop) { // check for composite indexes if (mb_strpos($prop, '+')) { $attributes = explode('+', $prop); $index_exists = false; foreach ($indexNames as $index) { if ($attributes[0] . '_' . $attributes[1] . '_unq_idx' == $index) { $index_exists = true; } if (count($attributes) == 3) { if ($attributes[0] . '_' . $attributes[1] . '_' . $attributes[2] . '_unq_idx' == $index) { $index_exists = true; } } } if (!$index_exists) { if (count($attributes) == 3) { $this->BO->createUniqueIndex($attributes[0], $attributes[1], $attributes[2]); } else { $this->BO->createUniqueIndex($attributes[0], $attributes[1]); } } } else { $index_exists = false; foreach ($indexNames as $index) { if ($prop . '_unq_idx' == $index) { $index_exists = true; } } if (!$index_exists) { $this->createUniqueIndex($prop); } } } // process foreign-key indexes // get the class attributes $reflection = new ReflectionClass(get_class($this->BO)); $properties = $reflection->getProperties(); foreach ($properties as $propObj) { $propName = $propObj->name; $prop = $this->BO->getPropObject($propName); if ($prop instanceof Relation) { if ($prop->getRelationType() == 'MANY-TO-ONE') { $indexExists = false; foreach ($indexNames as $index) { if ($this->BO->getTableName() . '_' . $propName . '_fk_idx' == $index) { $indexExists = true; } } if (!$indexExists) { $this->createForeignIndex($propName, $prop->getRelatedClass(), $prop->getRelatedClassField()); } } if ($prop->getRelationType() == 'MANY-TO-MANY') { $lookup = $prop->getLookup(); if ($lookup != null) { try { $lookupIndexNames = $lookup->getIndexes(); // handle index check/creation on left side of Relation $indexExists = false; foreach ($lookupIndexNames as $index) { if ($lookup->getTableName() . '_leftID_fk_idx' == $index) { $indexExists = true; } } if (!$indexExists) { $lookup->createForeignIndex('leftID', $prop->getRelatedClass('left'), 'OID'); } // handle index check/creation on right side of Relation $indexExists = false; foreach ($lookupIndexNames as $index) { if ($lookup->getTableName() . '_rightID_fk_idx' == $index) { $indexExists = true; } } if (!$indexExists) { $lookup->createForeignIndex('rightID', $prop->getRelatedClass('right'), 'OID'); } } catch (AlphaException $e) { self::$logger->error($e->getMessage()); } } } } } self::$logger->debug('<<checkIndexes'); }
/** * Handle an uncaught exception. * * @param Exception $e */ public static function catchException($e) { $logger = new Logger(get_class($e)); $logger->error($e->getMessage() . "\n [stacktrace]: \n" . $e->getTraceAsString()); }
/** * Checks to see if the person is in the rights group specified. * * @param string $groupName * * @return bool * * @since 1.0 */ public function inGroup($groupName) { if (self::$logger == null) { self::$logger = new Logger('Person'); } self::$logger->debug('>>inGroup(groupName=[' . $groupName . '])'); $group = new Rights(); try { $group->loadByAttribute('name', $groupName); } catch (RecordNotFoundException $e) { self::$logger->error('Unable to load the group named [' . $groupName . ']'); self::$logger->debug('<<inGroup [false]'); return false; } $rel = $group->getMembers(); try { // load all person2rights RelationLookup objects for this person $lookUps = $rel->getLookup()->loadAllByAttribute('leftID', $this->getID()); foreach ($lookUps as $lookUp) { // the rightID (i.e. Rights OID) will be on the right side of the value array $ids = $lookUp->getValue(); // if we have found a match, return true right away if ($ids[1] == $group->getID()) { self::$logger->debug('<<inGroup [true]'); return true; } } } catch (RecordNotFoundException $e) { self::$logger->debug('<<inGroup [false]'); return false; } self::$logger->debug('<<inGroup [false]'); return false; }
/** * Method to handle PUT requests. * * @param Alpha\Util\Http\Request * * @return Alpha\Util\Http\Response * * @since 1.0 */ public function doPUT($request) { self::$logger->debug('>>doPUT($request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $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!'); self::$logger->debug('<<doPUT'); } if (isset($params['markdownTextBoxRows']) && $params['markdownTextBoxRows'] != '') { $viewState = ViewState::getInstance(); $viewState->set('markdownTextBoxRows', $params['markdownTextBoxRows']); } if (isset($params['title']) || isset($params['ActiveRecordOID'])) { if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) { $record = new $params['ActiveRecordType'](); } else { $record = new Article(); } if (isset($params['title'])) { $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']); $record->loadByAttribute('title', $title, false, array('OID', 'version_num', 'created_ts', 'updated_ts', 'title', 'author', 'published', 'content', 'headerContent')); } else { $record->load($params['ActiveRecordOID']); } // uploading an article attachment if (isset($params['uploadBut'])) { $source = $request->getFile('userfile')['tmp_name']; $dest = $record->getAttachmentsLocation() . '/' . $request->getFile('userfile')['name']; // upload the file to the attachments directory FileUtils::copy($source, $dest); if (!file_exists($dest)) { throw new AlphaException('Could not move the uploaded file [' . $request->getFile('userfile')['name'] . ']'); } // set read/write permissions on the file $success = chmod($dest, 0666); if (!$success) { throw new AlphaException('Unable to set read/write permissions on the uploaded file [' . $dest . '].'); } if ($success) { self::$logger->action('File ' . $source . ' uploaded to ' . $dest); $this->setStatusMessage(View::displayUpdateMessage('File ' . $source . ' uploaded to ' . $dest)); } } elseif (isset($params['deletefile']) && $params['deletefile'] != '') { $success = unlink($record->getAttachmentsLocation() . '/' . $params['deletefile']); if (!$success) { throw new AlphaException('Could not delete the file [' . $params['deletefile'] . ']'); } if ($success) { self::$logger->action('File ' . $record->getAttachmentsLocation() . '/' . $params['deletefile'] . ' deleted'); $this->setStatusMessage(View::displayUpdateMessage('File ' . $record->getAttachmentsLocation() . '/' . $params['deletefile'] . ' deleted')); } } else { self::$logger->debug('<<doPUT'); return parent::doPUT($request); } } else { throw new IllegalArguementException('No valid article ID provided!'); } } catch (SecurityException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); self::$logger->warn($e->getMessage()); } catch (IllegalArguementException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); self::$logger->error($e->getMessage()); } catch (RecordNotFoundException $e) { self::$logger->warn($e->getMessage()); $this->setStatusMessage(View::displayErrorMessage('Failed to load the requested article from the database!')); } catch (AlphaException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); self::$logger->error($e->getMessage()); } $response = new Response(301); if ($this->getNextJob() != '') { $response->redirect($this->getNextJob()); } else { if ($this->request->isSecureURI()) { $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\\Model\\Article&ActiveRecordOID=' . $record->getOID() . '&view=edit')); } else { $title = str_replace(' ', $config->get('cms.url.title.separator'), $record->get('title')); $response->redirect($config->get('app.url') . '/a/' . $title . '/edit'); } } self::$logger->debug('<<doPUT'); return $response; }