/** * Testing the highlight() method. * * @since 2.0.1 * @dataProvider getHighlightProviders */ public function testHighlight($provider) { $highlighter = HighlightProviderFactory::getInstance($provider); $code = '<?= $value ?>'; $highlighted = $highlighter->highlight($code, 'php'); $this->assertNotEmpty($highlighted, 'Testing the highlight() method'); $this->assertTrue(Validator::isHTML($highlighted), 'Testing the highlight() method'); }
/** * 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; } }
/** * Builds a redirect response. * * @param string $URL The URL to redirect the client to. * * @throws Alpha\Exception\IllegalArguementException * * @since 2.0 */ public function redirect($URL) { if (Validator::isURL($URL)) { $this->headers = array(); $this->setHeader('Location', $URL); } else { throw new IllegalArguementException('Unable to redirect to URL [' . $URL . '] as it is invalid'); } }
/** * 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 GET requests. * * @param Alpha\Util\Http\Request $request * * @throws Alpha\Exception\ResourceNotFoundException * @throws Alpha\Exception\IllegalArguementException * * @return Alpha\Util\Http\Response * * @since 2.0 */ public function doGET($request) { self::$logger->debug('>>doGET(request=[' . var_export($request, true) . '])'); $config = ConfigProvider::getInstance(); $params = $request->getParams(); $accept = $request->getAccept(); $body = ''; try { // get a single record if (isset($params['ActiveRecordType']) && isset($params['ActiveRecordOID'])) { if (!Validator::isInteger($params['ActiveRecordOID'])) { throw new IllegalArguementException('Invalid oid [' . $params['ActiveRecordOID'] . '] provided on the request!'); } $ActiveRecordType = urldecode($params['ActiveRecordType']); if (class_exists($ActiveRecordType)) { $record = new $ActiveRecordType(); } else { throw new IllegalArguementException('No ActiveRecord available to view!'); } // set up the title and meta details if (isset($params['view']) && $params['view'] == 'edit') { if (!isset($this->title)) { $this->setTitle('Editing a ' . $record->getFriendlyClassName()); } if (!isset($this->description)) { $this->setDescription('Page to edit a ' . $record->getFriendlyClassName() . '.'); } if (!isset($this->keywords)) { $this->setKeywords('edit,' . $record->getFriendlyClassName()); } } else { if (!isset($this->title)) { $this->setTitle('Viewing a ' . $record->getFriendlyClassName()); } if (!isset($this->description)) { $this->setDescription('Page to view a ' . $record->getFriendlyClassName() . '.'); } if (!isset($this->keywords)) { $this->setKeywords('view,' . $record->getFriendlyClassName()); } } $record->load($params['ActiveRecordOID']); ActiveRecord::disconnect(); $view = View::getInstance($record, false, $accept); $body .= View::displayPageHead($this); $message = $this->getStatusMessage(); if (!empty($message)) { $body .= $message; } $body .= View::renderDeleteForm($request->getURI()); if (isset($params['view']) && $params['view'] == 'edit') { $fields = array('formAction' => $this->request->getURI()); $body .= $view->editView($fields); } else { $body .= $view->detailedView(); } } elseif (isset($params['ActiveRecordType']) && isset($params['start'])) { // list all records of this type $ActiveRecordType = urldecode($params['ActiveRecordType']); if (class_exists($ActiveRecordType)) { $record = new $ActiveRecordType(); } else { throw new IllegalArguementException('No ActiveRecord available to view!'); } // set up the title and meta details if (!isset($this->title)) { $this->setTitle('Listing all ' . $record->getFriendlyClassName()); } if (!isset($this->description)) { $this->setDescription('Listing all ' . $record->getFriendlyClassName()); } if (!isset($this->keywords)) { $this->setKeywords('list,all,' . $record->getFriendlyClassName()); } if (isset($this->filterField) && isset($this->filterValue)) { if (isset($this->sort) && isset($this->order)) { $records = $record->loadAllByAttribute($this->filterField, $this->filterValue, $params['start'], $params['limit'], $this->sort, $this->order); } else { $records = $record->loadAllByAttribute($this->filterField, $this->filterValue, $params['start'], $params['limit']); } $this->recordCount = $record->getCount(array($this->filterField), array($this->filterValue)); } else { if (isset($this->sort) && isset($this->order)) { $records = $record->loadAll($params['start'], $params['limit'], $this->sort, $this->order); } else { $records = $record->loadAll($params['start'], $params['limit']); } $this->recordCount = $record->getCount(); } ActiveRecord::disconnect(); $view = View::getInstance($record, false, $accept); $body .= View::displayPageHead($this); $message = $this->getStatusMessage(); if (!empty($message)) { $body .= $message; } $body .= View::renderDeleteForm($this->request->getURI()); foreach ($records as $record) { $view = View::getInstance($record, false, $accept); $fields = array('formAction' => $this->request->getURI()); $body .= $view->listView($fields); } if ($accept == 'application/json') { $body = rtrim($body, ','); } } elseif (isset($params['ActiveRecordType'])) { // create a new record of this type $ActiveRecordType = urldecode($params['ActiveRecordType']); if (class_exists($ActiveRecordType)) { $record = new $ActiveRecordType(); } else { throw new IllegalArguementException('No ActiveRecord available to create!'); } // set up the title and meta details if (!isset($this->title)) { $this->setTitle('Create a new ' . $record->getFriendlyClassName()); } if (!isset($this->description)) { $this->setDescription('Create a new ' . $record->getFriendlyClassName() . '.'); } if (!isset($this->keywords)) { $this->setKeywords('create,new,' . $record->getFriendlyClassName()); } $view = View::getInstance($record, false, $accept); $body .= View::displayPageHead($this); $fields = array('formAction' => $this->request->getURI()); $body .= $view->createView($fields); } else { throw new IllegalArguementException('No ActiveRecord available to display!'); } } catch (IllegalArguementException $e) { self::$logger->warn($e->getMessage()); throw new ResourceNotFoundException('The record that you have requested cannot be found!'); } catch (RecordNotFoundException $e) { self::$logger->warn($e->getMessage()); throw new ResourceNotFoundException('The record that you have requested cannot be found!'); } $body .= View::displayPageFoot($this); self::$logger->debug('<<doGET'); return new Response(200, $body, array('Content-Type' => $accept == 'application/json' ? 'application/json' : 'text/html')); }
/** * Setter for the value (OID of related object) of this relation. * * @param int $val * * @since 1.0 * * @throws Alpha\Exception\IllegalArguementException */ public function setValue($val) { if (empty($val)) { $this->value = null; } else { if (!Validator::isInteger($val)) { throw new IllegalArguementException("[{$val}]" . $this->helper); } if (mb_strlen($val) <= $this->size) { $this->value = str_pad($val, 11, '0', STR_PAD_LEFT); } else { throw new IllegalArguementException("[{$val}]" . $this->helper); } } }
/** * Accepts a string to set the Sequence prefix/sequence values to, in the * format PREFIX-00000000000. * * @param string $val * * @since 1.0 * * @throws Alpha\Exception\IllegalArguementException */ public function setValue($val) { if (mb_strlen($val) <= $this->size) { if (!empty($val)) { if (!Validator::isSequence($val)) { throw new IllegalArguementException($this->helper); } $parts = explode('-', $val); $this->prefix->setValue($parts[0]); $this->sequence->setValue($parts[1]); } } else { throw new IllegalArguementException($this->helper); } }
/** * Dynamically binds all of the attributes for the current BO to the supplied prepared statement * parameters. If arrays of attribute names and values are provided, only those will be bound to * the supplied statement. * * @param mysqli_stmt $stmt The SQL statement to bind to. * @param array Optional array of BO attributes. * @param array Optional array of BO values. * * @return mysqli_stmt * * @since 1.1 */ private function bindParams($stmt, $attributes = array(), $values = array()) { self::$logger->debug('>>bindParams(stmt=[' . var_export($stmt, true) . '])'); $bindingsTypes = ''; $params = array(); // here we are only binding the supplied attributes if (count($attributes) > 0 && count($attributes) == count($values)) { $count = count($values); for ($i = 0; $i < $count; ++$i) { if (Validator::isInteger($values[$i])) { $bindingsTypes .= 'i'; } else { $bindingsTypes .= 's'; } array_push($params, $values[$i]); } if ($this->BO->isTableOverloaded()) { if (isset($this->classname)) { $bindingsTypes .= 's'; array_push($params, $this->classname); } else { $bindingsTypes .= 's'; array_push($params, get_class($this->BO)); } } } else { // bind all attributes on the business object // get the class attributes $reflection = new ReflectionClass(get_class($this->BO)); $properties = $reflection->getProperties(); foreach ($properties as $propObj) { $propName = $propObj->name; if (!in_array($propName, $this->BO->getTransientAttributes())) { // Skip the OID, database auto number takes care of this. if ($propName != 'OID' && $propName != 'version_num') { if ($this->BO->getPropObject($propName) instanceof Integer) { $bindingsTypes .= 'i'; } else { $bindingsTypes .= 's'; } array_push($params, $this->BO->get($propName)); } if ($propName == 'version_num') { $temp = $this->BO->getVersionNumber()->getValue(); $this->BO->set('version_num', $temp + 1); $bindingsTypes .= 'i'; array_push($params, $this->BO->getVersionNumber()->getValue()); } } } if ($this->BO->isTableOverloaded()) { if (isset($this->classname)) { $bindingsTypes .= 's'; array_push($params, $this->classname); } else { $bindingsTypes .= 's'; array_push($params, get_class($this->BO)); } } // the OID may be on the WHERE clause for UPDATEs and DELETEs if (!$this->BO->isTransient()) { $bindingsTypes .= 'i'; array_push($params, $this->BO->getOID()); } } self::$logger->debug('bindingsTypes=[' . $bindingsTypes . '], count: [' . mb_strlen($bindingsTypes) . ']'); self::$logger->debug('params [' . var_export($params, true) . ']'); if ($params != null) { $bind_names[] = $bindingsTypes; $count = count($params); for ($i = 0; $i < $count; ++$i) { $bind_name = 'bind' . $i; ${$bind_name} = $params[$i]; $bind_names[] =& ${$bind_name}; } call_user_func_array(array($stmt, 'bind_param'), $bind_names); } self::$logger->debug('<<bindParams [' . var_export($stmt, true) . ']'); return $stmt; }
/** * Validate that the provided value is a base64 string. * * @since 1.2.3 */ public function testIsBase64() { $this->assertTrue(Validator::isBase64('YWJjZA==')); $this->assertTrue(Validator::isBase64('MTIzNA==')); $this->assertTrue(Validator::isBase64('YWJjZDEyMzQ=')); $this->assertFalse(Validator::isBase64('abcde')); $this->assertFalse(Validator::isBase64('12345')); $this->assertFalse(Validator::isBase64('abcde12345')); }
/** * Setter for the Integer value. * * @param int $val * * @since 1.0 * * @throws Alpha\Exception\IllegalArguementException */ public function setValue($val) { if (!Validator::isInteger($val)) { throw new IllegalArguementException($this->helper); } if (mb_strlen($val) <= $this->size) { $this->value = $val; } else { throw new IllegalArguementException($this->helper); } }
/** * Splits the passed content by spaces, filters (removes) stop words from stopwords.ini, * and returns an array of Tag instances. * * @param $content * @param $taggedClass Optionally provide a BO class name (with namespace) * @param $taggedOID Optionally provide a BO instance OID * @param $applyStopwords Defaults true, set to false if you want to ignore the stopwords. * * @return array * * @throws Alpha\Exception\AlphaException * * @since 1.0 */ public static function tokenize($content, $taggedClass = '', $taggedOID = '', $applyStopwords = true) { if (self::$logger == null) { self::$logger = new Logger('Tag'); } $config = ConfigProvider::getInstance(); // apply stop words $lowerWords = preg_split("/[\\s,.:-]+/", $content); array_walk($lowerWords, 'Alpha\\Model\\Tag::lowercaseArrayElement'); if ($applyStopwords) { if (file_exists($config->get('app.root') . 'config/stopwords-' . $config->get('search.stop.words.size') . '.ini')) { $stopwords = file($config->get('app.root') . 'config/stopwords-' . $config->get('search.stop.words.size') . '.ini', FILE_IGNORE_NEW_LINES); } elseif (file_exists($config->get('app.root') . 'Alpha/stopwords-' . $config->get('search.stop.words.size') . '.ini')) { $stopwords = file($config->get('app.root') . 'Alpha/stopwords-' . $config->get('search.stop.words.size') . '.ini', FILE_IGNORE_NEW_LINES); } else { throw new AlphaException('Unable to find a stopwords-' . $config->get('search.stop.words.size') . '.ini file in the application!'); } array_walk($stopwords, 'Alpha\\Model\\Tag::lowercaseArrayElement'); $filtered = array_diff($lowerWords, $stopwords); } else { $filtered = $lowerWords; } $tagObjects = array(); $tagContents = array(); foreach ($filtered as $tagContent) { // we only want to create word tags if (Validator::isAlpha($tagContent)) { // just making sure that we haven't added this one in already if (!in_array($tagContent, $tagContents) && !empty($tagContent)) { $tag = new self(); $tag->set('content', trim(mb_strtolower($tagContent))); if (!empty($taggedClass)) { $tag->set('taggedClass', $taggedClass); } if (!empty($taggedOID)) { $tag->set('taggedOID', $taggedOID); } array_push($tagObjects, $tag); array_push($tagContents, $tagContent); } } } self::$logger->debug('Tags generated: [' . var_export($tagContents, true) . ']'); return $tagObjects; }
/** * Descrypts the HTTP param fieldnames in the array provided and returns the plain version. * * @param $params array * * @return array * * @since 1.2.2 */ private function decryptFieldNames($params) { $decrypted = array(); foreach (array_keys($params) as $fieldname) { // set request params where fieldnames provided are based64 encoded and encrypted if (Validator::isBase64($fieldname)) { $decrypted[SecurityUtils::decrypt(base64_decode($fieldname))] = $params[$fieldname]; } } return $decrypted; }
/** * Used to set the Boolean value. * * @param mixed $val Will accept a boolean true/false or integer 1/0. * * @since 1.0 * * @throws Alpha\Exception\IllegalArguementException */ public function setValue($val) { if (!Validator::isBoolean($val)) { throw new IllegalArguementException($this->helper); } if (Validator::isBooleanTrue($val)) { $this->value = 1; $this->booleanValue = true; } else { $this->value = 0; $this->booleanValue = false; } }