public function getFieldHTML($field, $required) { $required = $field->required == 1 ? ' data-required="true"' : ''; //a fix for wrong data $field->value = JString::trim($field->value); if (JString::strrpos($field->value, ',') == JString::strlen($field->value) - 1) { $field->value = JString::substr($field->value, 0, -1); } $lists = explode(',', $field->value); //CFactory::load( 'helpers' , 'string' ); $html = '<select id="field' . $field->id . '" name="field' . $field->id . '[]" type="select-multiple" multiple="multiple" class="joms-select joms-select--multiple" title="' . CStringHelper::escape(JText::_($field->tips)) . '" ' . $required . '>'; $elementSelected = 0; foreach ($field->options as $option) { $selected = in_array($option, $lists) ? ' selected="selected"' : ''; if (empty($selected)) { $elementSelected++; } $html .= '<option value="' . $option . '"' . $selected . '>' . JText::_($option) . '</option>'; } if ($elementSelected == 0) { //if nothing is selected, we default the 1st option to be selected. $elementName = 'field' . $field->id; $html .= <<<HTML <script type='text/javascript'> var slt = document.getElementById('{$elementName}'); if(slt != null){ slt.options[0].selected = true; } </script> HTML; } $html .= '</select>'; return $html; }
/** * Truncates text blocks over the specified character limit and closes * all open HTML tags. The method will optionally not truncate an individual * word, it will find the first space that is within the limit and * truncate at that point. This method is UTF-8 safe. * * @param string $text The text to truncate. * @param integer $length The maximum length of the text. * @param boolean $noSplit Don't split a word if that is where the cutoff occurs (default: true). * @param boolean $allowHtml Allow HTML tags in the output, and close any open tags (default: true). * * @return string The truncated text. * * @since 11.1 */ public static function truncate($text, $length = 0, $noSplit = true, $allowHtml = true) { // Check if HTML tags are allowed. if (!$allowHtml) { // Deal with spacing issues in the input. $text = str_replace('>', '> ', $text); $text = str_replace(array(' ', ' '), ' ', $text); $text = JString::trim(preg_replace('#\\s+#mui', ' ', $text)); // Strip the tags from the input and decode entities. $text = strip_tags($text); $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); // Remove remaining extra spaces. $text = str_replace(' ', ' ', $text); $text = JString::trim(preg_replace('#\\s+#mui', ' ', $text)); } // Truncate the item text if it is too long. if ($length > 0 && JString::strlen($text) > $length) { // Find the first space within the allowed length. $tmp = JString::substr($text, 0, $length); if ($noSplit) { $offset = JString::strrpos($tmp, ' '); if (JString::strrpos($tmp, '<') > JString::strrpos($tmp, '>')) { $offset = JString::strrpos($tmp, '<'); } $tmp = JString::substr($tmp, 0, $offset); // If we don't have 3 characters of room, go to the second space within the limit. if (JString::strlen($tmp) > $length - 3) { $tmp = JString::substr($tmp, 0, JString::strrpos($tmp, ' ')); } } if ($allowHtml) { // Put all opened tags into an array preg_match_all("#<([a-z][a-z0-9]*)\\b.*?(?!/)>#i", $tmp, $result); $openedTags = $result[1]; $openedTags = array_diff($openedTags, array("img", "hr", "br")); $openedTags = array_values($openedTags); // Put all closed tags into an array preg_match_all("#</([a-z]+)>#iU", $tmp, $result); $closedTags = $result[1]; $numOpened = count($openedTags); // All tags are closed if (count($closedTags) == $numOpened) { return $tmp . '...'; } $openedTags = array_reverse($openedTags); // Close tags for ($i = 0; $i < $numOpened; $i++) { if (!in_array($openedTags[$i], $closedTags)) { $tmp .= "</" . $openedTags[$i] . ">"; } else { unset($closedTags[array_search($openedTags[$i], $closedTags)]); } } } $text = $tmp . '...'; } return $text; }
/** * Truncates text blocks over the specified character limit and closes * all open HTML tags. The behavior will not truncate an individual * word, it will find the first space that is within the limit and * truncate at that point. This method is UTF-8 safe. * * @param string $text The text to truncate. * @param integer $length The maximum length of the text. * * @return string The truncated text. * * @since 11.1 */ public static function truncate($text, $length = 0) { // Truncate the item text if it is too long. if ($length > 0 && JString::strlen($text) > $length) { // Find the first space within the allowed length. $tmp = JString::substr($text, 0, $length); $offset = JString::strrpos($tmp, ' '); if (JString::strrpos($tmp, '<') > JString::strrpos($tmp, '>')) { $offset = JString::strrpos($tmp, '<'); } $tmp = JString::substr($tmp, 0, $offset); // If we don't have 3 characters of room, go to the second space within the limit. if (JString::strlen($tmp) >= $length - 3) { $tmp = JString::substr($tmp, 0, JString::strrpos($tmp, ' ')); } // Put all opened tags into an array preg_match_all("#<([a-z][a-z0-9]?)( .*)?(?!/)>#iU", $tmp, $result); $openedtags = $result[1]; $openedtags = array_diff($openedtags, array("img", "hr", "br")); $openedtags = array_values($openedtags); // Put all closed tags into an array preg_match_all("#</([a-z]+)>#iU", $tmp, $result); $closedtags = $result[1]; $len_opened = count($openedtags); // All tags are closed if (count($closedtags) == $len_opened) { return $tmp . '...'; } $openedtags = array_reverse($openedtags); // Close tags for ($i = 0; $i < $len_opened; $i++) { if (!in_array($openedtags[$i], $closedtags)) { $tmp .= "</" . $openedtags[$i] . ">"; } else { unset($closedtags[array_search($openedtags[$i], $closedtags)]); } } $text = $tmp . '...'; } return $text; }
public function getFieldHTML($field, $required) { $lists = array(); //a fix for wrong data input $field->value = JString::trim($field->value); if (is_array($field->value)) { $tmplist = $field->value; } else { if (JString::strrpos($field->value, ',') == JString::strlen($field->value) - 1) { $field->value = JString::substr($field->value, 0, -1); } $tmplist = explode(',', $field->value); } if ($tmplist) { foreach ($tmplist as $value) { $lists[] = JString::trim($value); } } $html = ''; $elementSelected = 0; $elementCnt = 0; $cnt = 0; $params = new CParameter($field->params); $readonly = ''; if ($params->get('readonly') == 1) { $readonly = ' disabled="disabled"'; } $html .= '<div style="display:inline-block">'; if (is_array($field->options)) { foreach ($field->options as $option) { if (JString::trim($option) == '') { //do not display blank options continue; } $selected = in_array(JString::trim($option), $lists) ? ' checked="checked"' : ''; if (empty($selected)) { $elementSelected++; } $html .= '<label class="lblradio-block">'; $html .= '<input type="checkbox" name="field' . $field->id . '[]" value="' . $option . '" class="joms-checkbox" ' . $selected . $readonly . ' style="margin: 2px 5px 0 0" />'; $html .= JText::_($option) . '</label>'; $elementCnt++; } } $html .= '</div>'; return $html; }
/** * Crop string into given length. * Method strip HTML tags and crop string to given length after last space. * From croped string strip all characters which are not letter or number. * At the end of string add tail according to language constant JOOMDOC_CROP. * * @param string $text string to crop * @param int $length crop length * @return string */ public static function crop($text, $length) { $chars = '~;!?.,@#$%^&*_-=+{}[]()<>:|"\'´`//\\'; $text = strip_tags($text); $text = parent::trim($text); if (parent::strlen($text) <= $length) { return $text; } $text = parent::substr($text, 0, $length); $lastSpace = parent::strrpos($text, ' '); $text = parent::substr($text, 0, $lastSpace); $text = parent::trim($text); while ($length = parent::strlen($text)) { $lastChar = parent::substr($text, $length - 2, 1); if (parent::strpos($chars, $lastChar) !== false) { $text = parent::substr($text, 0, $length - 1); } else { break; } } return JText::sprintf('JOOMDOC_CROP', $text); }
protected static function truncateText($string, $limit) { $prevSpace = JString::strrpos(JString::substr($string, 0, $limit), ' '); $prevLength = $prevSpace !== false ? $limit - max(0, $prevSpace) : $limit; $nextSpace = JString::strpos($string, ' ', $limit + 1); $nextLength = $nextSpace !== false ? max($nextSpace, $limit) - $limit : $limit; $length = 0; if ($prevSpace !== false && $nextSpace !== false) { $length = $prevLength < $nextLength ? $prevSpace : $nextSpace; } elseif ($prevSpace !== false && $nextSpace === false) { $length = $length - $prevLength < $length * 0.1 ? $prevSpace : $length; } elseif ($prevSpace === false && $nextSpace !== false) { $length = $nextLength - $length < $length * 0.1 ? $nextSpace : $length; } if ($length > 0) { $limit = $length; } $text = JString::substr($string, 0, $limit); if (!preg_match('#(\\.|\\?|\\!)$#ismu', $text)) { $text = preg_replace('#\\s?(\\,|\\;|\\:|\\-)$#ismu', '', $text) . ' ...'; } return $text; }
function getReadmore($text, $length = null) { $text = strip_tags($text); $text = JString::trim($text); if ($length) { $text = JString::substr($text, 0, $length + 1); $last = JString::strrpos($text, ' '); if ($last) { $text = JString::substr($text, 0, $last); $run = true; while ($run) { $slength = JString::strlen($text); if ($slength == 0) { break; } $last = JString::substr($text, $slength - 1, 1); switch ($last) { case '.': case ',': case '_': case '-': $text = JString::substr($text, 0, $slength - 1); break; default: $run = false; break; } } $text .= ' ...'; } } return $text; }
/** * @group String * @covers JString::strrpos * @dataProvider strrposData */ public function testStrrpos($haystack, $needle, $offset = 0, $expect) { $actual = JString::strrpos($haystack, $needle, $offset); $this->assertEquals($expect, $actual); }
/** * Get path to payment files. * * @param string $alias * @return array */ function payment($alias) { return array('button' => ($base = PAYMENTS . DS . JString::substr($alias, 0, JString::strrpos($alias, '_')) . DS) . 'button.php', 'config' => $base . 'config.xml', 'controller' => $base . 'controller.php', 'icon' => $base . 'icon.png'); }
/** * Clip text to use as meta description * * @param string $text * @param int $limit * @return string */ function clipDesc($text, $limit) { if (JString::strlen($text) > $limit) { $text = JString::substr($text, 0, $limit); $pos = JString::strrpos($text, ' '); if ($pos !== false) { $text = JString::substr($text, 0, $pos); } $text = JString::trim($text); } return $text; }
public function mapAvatar($avatarUrl = '', $joomlaUserId, $addWaterMark) { $image = ''; if (!empty($avatarUrl)) { // Make sure user is properly added into the database table first $user = CFactory::getUser($joomlaUserId); $fbUser = $this->getUser(); // Load image helper library as it is needed. CFactory::load('helpers', 'image'); // Store image on a temporary folder. $tmpPath = JPATH_ROOT . DS . 'images' . DS . 'originalphotos' . DS . 'facebook_connect_' . $fbUser; /* print_r($avatarUrl); exit; $url = parse_url( $avatarUrl ); $host = $url[ 'host' ]; $fp = fsockopen("profile.ak.fbcdn.net", 80, $errno, $errstr, 30); $path = CString::str_ireplace( $url['scheme'] . '://' . $host , '' , $avatarUrl ); $source = ''; if( $fp ) { $out = "GET $path HTTP/1.1\r\n"; $out .= "Host: " . $host . "\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); $body = false; while( !feof( $fp ) ) { $return = fgets( $fp , 1024 ); if( $body ) { $source .= $return; } if( $return == "\r\n" ) { $body = true; } } fclose($fp); } */ // Need to extract the non-https version since it will cause // certificate issue $avatarUrl = str_replace('https://', 'http://', $avatarUrl); CFactory::load('helpers', 'remote'); $source = CRemoteHelper::getContent($avatarUrl, true); list($headers, $source) = explode("\r\n\r\n", $source, 2); JFile::write($tmpPath, $source); // @todo: configurable width? $imageMaxWidth = 160; // Get a hash for the file name. $fileName = JUtility::getHash($fbUser . time()); $hashFileName = JString::substr($fileName, 0, 24); $extension = JString::substr($avatarUrl, JString::strrpos($avatarUrl, '.')); $type = 'image/jpg'; if ($extension == '.png') { $type = 'image/png'; } if ($extension == '.gif') { $type = 'image/gif'; } //@todo: configurable path for avatar storage? $config = CFactory::getConfig(); $storage = JPATH_ROOT . DS . $config->getString('imagefolder') . DS . 'avatar'; $storageImage = $storage . DS . $hashFileName . $extension; $storageThumbnail = $storage . DS . 'thumb_' . $hashFileName . $extension; $image = $config->getString('imagefolder') . '/avatar/' . $hashFileName . $extension; $thumbnail = $config->getString('imagefolder') . '/avatar/' . 'thumb_' . $hashFileName . $extension; $userModel = CFactory::getModel('user'); // Only resize when the width exceeds the max. CImageHelper::resizeProportional($tmpPath, $storageImage, $type, $imageMaxWidth); CImageHelper::createThumb($tmpPath, $storageThumbnail, $type); if ($addWaterMark) { // Get the width and height so we can calculate where to place the watermark. list($watermarkWidth, $watermarkHeight) = getimagesize(FACEBOOK_FAVICON); list($imageWidth, $imageHeight) = getimagesize($storageImage); list($thumbWidth, $thumbHeight) = getimagesize($storageThumbnail); CImageHelper::addWatermark($storageImage, $storageImage, $type, FACEBOOK_FAVICON, $imageWidth - $watermarkWidth, $imageHeight - $watermarkHeight); CImageHelper::addWatermark($storageThumbnail, $storageThumbnail, $type, FACEBOOK_FAVICON, $thumbWidth - $watermarkWidth, $thumbHeight - $watermarkHeight); } // Update the CUser object with the correct avatar. $user->set('_thumb', $thumbnail); $user->set('_avatar', $image); // @rule: once user changes their profile picture, storage method should always be file. $user->set('_storage', 'file'); $userModel->setImage($joomlaUserId, $image, 'avatar'); $userModel->setImage($joomlaUserId, $thumbnail, 'thumb'); $user->save(); } }
/** * Get meta description text format. Clean text and crop to 150 characters. * * @param string $text * @return string */ public static function getMetaDescriptions($text) { $text = JFilterOutput::cleanText($text); $text = JString::trim($text); if (JString::strlen($text) <= 150) { return $text; } $text = JString::substr($text, 0, 150); $lastFullStop = JString::strrpos($text, '.'); if ($lastFullStop !== false) { $text = JString::substr($text, 0, $lastFullStop + 1); } $text = JString::trim($text); return $text; }
/** * Get path of parent folder from path. * * @param string $path * @return string */ public static function getParentPath($path) { if (($pos = JString::strrpos($path, DIRECTORY_SEPARATOR)) === false) { return null; } return JString::substr($path, 0, $pos); }
public function prepareAudio($data, $file = null, $_copy = false) { $copy = $_copy; if ($this->tztask) { $copy = true; } if ($data) { if (isset($data['jform'])) { $data = $data['jform']; } if ($data['audio_soundcloud_id']) { $fileTypes = array('image/jpeg', 'image/jpg', 'image/bmp', 'image/gif', 'image/png', 'image/ico'); $params = $this->getState('params'); $_data = null; $_data = $this->_db->quote($data['audio_soundcloud_id']); $id = $this->getState($this->getName() . '.id'); if (!$id) { $id = $data['id']; } // Create folder to save thumb if this folder isn't created. $audioPath = $this->imageUrl . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'thumbnail' . DIRECTORY_SEPARATOR . $this->audioFolder; if (!JFolder::exists(JPATH_SITE . DIRECTORY_SEPARATOR . $audioPath)) { JFolder::create(JPATH_SITE . DIRECTORY_SEPARATOR . $audioPath); } if (JFolder::exists(JPATH_SITE . DIRECTORY_SEPARATOR . $audioPath)) { if (!JFile::exists(JPATH_SITE . DIRECTORY_SEPARATOR . $audioPath . DIRECTORY_SEPARATOR . 'index.html')) { JFile::write(JPATH_SITE . DIRECTORY_SEPARATOR . $audioPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>')); } } // Check and set chmod folder again $chmodFolder = JPath::getPermissions($audioPath); if ($chmodFolder != 'rwxrwxrwx' || $chmodFolder != 'rwxr-xr-x') { JPath::setPermissions($audioPath); } // Prepare data (Return string to save the database) //// Delete old thumbnail if delete checkbox input is checked if ($data['audio_soundcloud_delete_image'] && ($hiddenImage = $data['audio_soundcloud_hidden_image'])) { $this->deleteThumb(null, $hiddenImage); // // Delete old original thumbnail // $org_path = JPATH_SITE.DIRECTORY_SEPARATOR.$org_audioPath.DIRECTORY_SEPARATOR // .JFile::getName($data['audio_soundcloud_hidden_image']); // if(JFile::exists($org_path)){ // JFile::delete($org_path); // } } if ($file && !empty($file['name'])) { // If choose thumbnail from client $destName = (!$data['alias'] ? uniqid() . 'tz_portfolio_' . time() : $data['alias']) . '-' . $id . '.' . JFile::getExt($file['name']); $image = $this->uploadImageClient($file, $destName, $audioPath, $fileTypes, $this->_getImageSizes($params), $data['audio_soundcloud_hidden_image']); } elseif (!empty($data['audio_soundcloud_image_server'])) { // If choose thumbnail from server $destName = (!$data['alias'] ? uniqid() . 'tz_portfolio_' . time() : $data['alias']) . '-' . $id . '.' . JFile::getExt($data['audio_soundcloud_image_server']); $image = $this->uploadImageServer($data['audio_soundcloud_image_server'], $destName, $audioPath, $this->_getImageSizes($params), $data['audio_soundcloud_hidden_image'], $copy); } else { // Get thumbnail from soundcloud page if ($data['audio_soundcloud_delete_image'] && ($hiddenImage = $data['audio_soundcloud_hidden_image'])) { $data['audio_soundcloud_hidden_image'] = ''; } if (!isset($data['audio_soundcloud_hidden_image']) || empty($data['audio_soundcloud_hidden_image'])) { if ($client_id = $params->get('soundcloud_client_id', '4a24c193db998e3b88c34cad41154055')) { // Register fetch object $fetch = new Services_Yadis_PlainHTTPFetcher(); $url = 'http://api.soundcloud.com/tracks/' . $data['audio_soundcloud_id'] . '.json?client_id=' . $client_id; if ($content = $fetch->get($url)) { $content = json_decode($content->body); $thumbUrl = null; if ($content->artwork_url && !empty($content->artwork_url)) { $thumbUrl = $content->artwork_url; } else { $audioUser = $content->user; if ($audioUser->avatar_url && !empty($audioUser->avatar_url)) { $thumbUrl = $audioUser->avatar_url; } } if ($thumbUrl) { if (JString::strrpos($thumbUrl, '-', 0) != false) { $thumbUrl = JString::substr($thumbUrl, 0, JString::strrpos($thumbUrl, '-', 0) + 1) . 't500x500.' . JFile::getExt($thumbUrl); } // Create folder tmp if not exists if (!JFolder::exists(JPATH_SITE . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $this->tzfolder)) { JFolder::create(JPATH_SITE . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $this->tzfolder); } if (JFolder::exists(JPATH_SITE . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $this->tzfolder)) { if (!JFile::exists(JPATH_SITE . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $this->tzfolder . 'index.html')) { JFile::write(JPATH_SITE . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $this->tzfolder . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>')); } } // Save image from other server to this server (temp file) $fetch2 = new Services_Yadis_PlainHTTPFetcher(); $audioTempPath = null; if ($audioTemp = $fetch2->get($thumbUrl)) { if (in_array($audioTemp->headers['Content-Type'], $fileTypes)) { $audioType = JFile::getExt($thumbUrl); if (preg_match('/(.*)(\\|\\/|\\:|\\*|\\?|\\"|\\<|\\>|\\|.*?)/i', $audioType, $match)) { $audioType = $match[1]; } $audioTempPath = 'media' . DIRECTORY_SEPARATOR . $this->tzfolder . DIRECTORY_SEPARATOR . uniqid() . time() . '.' . $audioType; JFile::write(JPATH_SITE . DIRECTORY_SEPARATOR . $audioTempPath, $audioTemp->body); } } if ($audioTempPath) { $destName = (!$data['alias'] ? uniqid() . 'tz_portfolio_' . time() : $data['alias']) . '-' . $id . '.' . JFile::getExt($audioTempPath); $image = $this->uploadImageServer($audioTempPath, $destName, $audioPath, $this->_getImageSizes($params)); if (JFile::exists(JPATH_SITE . DIRECTORY_SEPARATOR . $audioTempPath)) { JFile::delete(JPATH_SITE . DIRECTORY_SEPARATOR . $audioTempPath); } } } } } } else { $image = $data['audio_soundcloud_hidden_image']; } } $_data .= ','; if ($image) { $_data .= $this->_db->quote($image); } else { $_data .= $this->_db->quote(''); } $_data .= ','; if ($data['audio_soundcloud_title']) { $_data .= $this->_db->quote($data['audio_soundcloud_title']); } else { $_data .= $this->_db->quote(''); } return $_data; } if ($data['audio_soundcloud_hidden_image']) { $this->deleteThumb(null, $data['audio_soundcloud_hidden_image']); } return $this->_db->quote('') . ',' . $this->_db->quote('') . ',' . $this->_db->quote(''); } return $this->_db->quote('') . ',' . $this->_db->quote('') . ',' . $this->_db->quote(''); }
/** * Alternative to @truncater to truncate contents with HTML codes * * @since 1.3 * @access public * @param string * @return */ public static function truncate($text, $length = 250, $ending = '', $exact = false) { // Load site's language file FD::language()->loadSite(); if (!$ending) { $ending = JText::_('COM_EASYSOCIAL_ELLIPSES'); } // If the plain text is shorter than the maximum length, return the whole text if (JString::strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = JString::strlen($ending); $open_tags = array(); $truncate = ''; foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash if (preg_match('/^<(\\s*.+?\\/\\s*|\\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag } else { if (preg_match('/^<\\s*\\/([^\\s]+?)\\s*>$/s', $line_matchings[1], $tag_matchings)) { // delete tag from $open_tags list $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } // if tag is an opening tag } else { if (preg_match('/^<\\s*([^\\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { // add tag to the beginning of $open_tags list array_unshift($open_tags, JString::strtolower($tag_matchings[1])); } } } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = JString::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length + $content_length > $length) { // the number of characters which are left $left = $length - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1] + 1 - $entities_length <= $left) { $left--; $entities_length += JString::strlen($entity[0]); } else { // no more characters left break; } } } $truncate .= JString::substr($line_matchings[2], 0, $left + $entities_length); // maximum lenght is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if ($total_length >= $length) { break; } } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurance of a space... $spacepos = JString::strrpos($truncate, ' '); if (isset($spacepos)) { // ...and cut the text in this position $truncate = JString::substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; // close all unclosed html-tags foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } $uid = uniqid(); $theme = FD::themes(); $theme->set('truncated', $truncate); $theme->set('uid', $uid); $theme->set('text', $text); $output = $theme->output('admin/html/string.truncate'); return $output; }
public function mapAvatar($avatarUrl = '', $joomlaUserId, $addWaterMark) { $image = ''; if (!empty($avatarUrl)) { // Make sure user is properly added into the database table first $user = CFactory::getUser($joomlaUserId); $fbUser = $this->getUser(); // Store image on a temporary folder. $tmpPath = JPATH_ROOT . '/images/originalphotos/facebook_connect_' . $fbUser; // Need to extract the non-https version since it will cause // certificate issue $avatarUrl = str_replace('https://', 'http://', $avatarUrl); $source = CRemoteHelper::getContent($avatarUrl, true); list($headers, $source) = explode("\r\n\r\n", $source, 2); JFile::write($tmpPath, $source); // @todo: configurable width? $imageMaxWidth = 160; // Get a hash for the file name. $fileName = JApplication::getHash($fbUser . time()); $hashFileName = JString::substr($fileName, 0, 24); $uri_parts = explode('?', $avatarUrl, 2); $extension = JString::substr($uri_parts[0], JString::strrpos($uri_parts[0], '.')); $type = 'image/jpg'; if ($extension == '.png') { $type = 'image/png'; } if ($extension == '.gif') { $type = 'image/gif'; } //@todo: configurable path for avatar storage? $config = CFactory::getConfig(); $storage = JPATH_ROOT . '/' . $config->getString('imagefolder') . '/avatar'; $storageImage = $storage . '/' . $hashFileName . $extension; $storageThumbnail = $storage . '/thumb_' . $hashFileName . $extension; $image = $config->getString('imagefolder') . '/avatar/' . $hashFileName . $extension; $thumbnail = $config->getString('imagefolder') . '/avatar/' . 'thumb_' . $hashFileName . $extension; $userModel = CFactory::getModel('user'); // Only resize when the width exceeds the max. CImageHelper::resizeProportional($tmpPath, $storageImage, $type, $imageMaxWidth); CImageHelper::createThumb($tmpPath, $storageThumbnail, $type); if ($addWaterMark) { // Get the width and height so we can calculate where to place the watermark. list($watermarkWidth, $watermarkHeight) = getimagesize(FACEBOOK_FAVICON); list($imageWidth, $imageHeight) = getimagesize($storageImage); list($thumbWidth, $thumbHeight) = getimagesize($storageThumbnail); CImageHelper::addWatermark($storageImage, $storageImage, $type, FACEBOOK_FAVICON, $imageWidth - $watermarkWidth, $imageHeight - $watermarkHeight); CImageHelper::addWatermark($storageThumbnail, $storageThumbnail, $type, FACEBOOK_FAVICON, $thumbWidth - $watermarkWidth, $thumbHeight - $watermarkHeight); } // Update the CUser object with the correct avatar. $user->set('_thumb', $thumbnail); $user->set('_avatar', $image); // @rule: once user changes their profile picture, storage method should always be file. $user->set('_storage', 'file'); $userModel->setImage($joomlaUserId, $image, 'avatar'); $userModel->setImage($joomlaUserId, $thumbnail, 'thumb'); $user->save(); } }
public function saveAvatarFromURL($url) { $tmpPath = JPATH_ROOT . DS . 'images'; $my = CFactory::getUser(); // Need to extract the non-https version since it will cause // certificate issue $avatarUrl = str_replace('https://', 'http://', $url); CFactory::load('helpers', 'remote'); $source = CRemoteHelper::getContent($url, true); JFile::write($tmpPath, $source); // @todo: configurable width? $imageMaxWidth = 160; // Get a hash for the file name. $fileName = JUtility::getHash($my->getDisplayName() . time()); $hashFileName = JString::substr($fileName, 0, 24); $extension = JString::substr($url, JString::strrpos($url, '.')); $type = 'image/jpg'; if ($extension == '.png') { $type = 'image/png'; } if ($extension == '.gif') { $type = 'image/gif'; } //@todo: configurable path for avatar storage? $config = CFactory::getConfig(); $storage = JPATH_ROOT . DS . $config->getString('imagefolder') . DS . 'avatar'; $storageImage = $storage . DS . $hashFileName . $extension; $storageThumbnail = $storage . DS . 'thumb_' . $hashFileName . $extension; $image = $config->getString('imagefolder') . '/avatar/' . $hashFileName . $extension; $thumbnail = $config->getString('imagefolder') . '/avatar/' . 'thumb_' . $hashFileName . $extension; $userModel = CFactory::getModel('user'); // Only resize when the width exceeds the max. CImageHelper::resizeProportional($tmpPath, $storageImage, $type, $imageMaxWidth); CImageHelper::createThumb($tmpPath, $storageThumbnail, $type); $removeOldImage = false; $userModel->setImage($my->id, $image, 'avatar', $removeOldImage); $userModel->setImage($my->id, $thumbnail, 'thumb', $removeOldImage); // Update the user object so that the profile picture gets updated. $my->set('_avatar', $image); $my->set('_thumb', $thumbnail); return true; }
/** * Get truncated string (by words) * @param $string * @param $maxlen * @return string */ public function cutByWords($string, $maxlen = 255) { $len = JString::strlen($string) > $maxlen ? JString::strrpos(JString::substr($string, 0, $maxlen), ' ') : $maxlen; $cutStr = JString::substr($string, 0, $len); return JString::strlen($string) > $maxlen ? $cutStr . '...' : $cutStr; }
public static function truncateHtml($text, $length = 320, $ending = '…', $exact = false, $considerHtml = true) { if ($considerHtml) { if (JString::strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $open_tags = array(); $total_length = 0; $truncate = ''; foreach ($lines AS $line_matchings) { if (!empty($line_matchings[1])) { if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { } else { if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } } else { if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { array_unshift($open_tags, strtolower($tag_matchings[1])); } } } $truncate .= $line_matchings[1]; } $content_length = JString::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length + $content_length > $length) { $left = $length - $total_length; $entities_length = 0; if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { foreach ($entities[0] AS $entity) { if ($entity[1] + 1 - $entities_length <= $left) { $left--; $entities_length += JString::strlen($entity[0]); } else { break; } } } $truncate .= JString::substr($line_matchings[2], 0, $left + $entities_length); break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } if ($total_length >= $length) { break; } } } else { if (JString::strlen($text) <= $length) { return $text; } else { $truncate = JString::substr($text, 0, $length); } } if (!$exact && $length > 10) { $spacepos = JString::strrpos($truncate, ' '); if (isset($spacepos)) { $truncate = JString::substr($truncate, 0, $spacepos); } } $truncate .= $ending; if ($considerHtml) { foreach ($open_tags AS $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; }
function ignoreHtml($text, $length = 100, $ending = '…', $exact = false, $considerHtml = true) { $text = JHtml::_('content.prepare', $text); $text = preg_replace("/<img(.*)>/msU", "", $text); if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text if (JString::strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $open_tags = array(); $total_length = $truncate = ''; foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash if (preg_match('/^<(\\s*.+?\\/\\s*|\\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag } elseif (preg_match('/^<\\s*\\/([^\\s]+?)\\s*>$/s', $line_matchings[1], $tag_matchings)) { // delete tag from $open_tags list $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } // if tag is an opening tag } elseif (preg_match('/^<\\s*([^\\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { // add tag to the beginning of $open_tags list array_unshift($open_tags, strtolower($tag_matchings[1])); } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = JString::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length + $content_length > $length) { // the number of characters which are left $left = $length - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities["0"] as $entity) { if ($entity[1] + 1 - $entities_length <= $left) { $left--; $entities_length += JString::strlen($entity["0"]); } else { // no more characters left break; } } } $truncate .= JString::substr($line_matchings[2], 0, $left + $entities_length); // maximum lenght is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if ($total_length >= $length) { break; } } } else { if (JString::strlen($text) <= $length) { return $text; } else { $truncate = JString::substr($text, 0, $length); } } // if the words shouldn't be cut in the middle... if (!$exact && $length > 10) { $spacepos = JString::strrpos($truncate, ' '); if (isset($spacepos)) { $truncate = JString::substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; // close all unclosed html-tags if ($considerHtml) { foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; }
/** * Truncates text blocks over the specified character limit and closes * all open HTML tags. The method will optionally not truncate an individual * word, it will find the first space that is within the limit and * truncate at that point. This method is UTF-8 safe. * * @param string $text The text to truncate. * @param integer $length The maximum length of the text. * @param boolean $noSplit Don't split a word if that is where the cutoff occurs (default: true). * @param boolean $allowHtml Allow HTML tags in the output, and close any open tags (default: true). * * @return string The truncated text. * * @since 1.6 */ public static function truncate($text, $length = 0, $noSplit = true, $allowHtml = true) { // Assume a lone open tag is invalid HTML. if ($length == 1 && substr($text, 0, 1) == '<') { return '...'; } // Check if HTML tags are allowed. if (!$allowHtml) { // Deal with spacing issues in the input. $text = str_replace('>', '> ', $text); $text = str_replace(array(' ', ' '), ' ', $text); $text = JString::trim(preg_replace('#\\s+#mui', ' ', $text)); // Strip the tags from the input and decode entities. $text = strip_tags($text); $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); // Remove remaining extra spaces. $text = str_replace(' ', ' ', $text); $text = JString::trim(preg_replace('#\\s+#mui', ' ', $text)); } // Whether or not allowing HTML, truncate the item text if it is too long. if ($length > 0 && JString::strlen($text) > $length) { $tmp = trim(JString::substr($text, 0, $length)); if (substr($tmp, 0, 1) == '<' && strpos($tmp, '>') === false) { return '...'; } // $noSplit true means that we do not allow splitting of words. if ($noSplit) { // Find the position of the last space within the allowed length. $offset = JString::strrpos($tmp, ' '); $tmp = JString::substr($tmp, 0, $offset + 1); // If there are no spaces and the string is longer than the maximum // we need to just use the ellipsis. In that case we are done. if ($offset === false && strlen($text) > $length) { return '...'; } if (JString::strlen($tmp) > $length - 3) { $tmp = trim(JString::substr($tmp, 0, JString::strrpos($tmp, ' '))); } } if ($allowHtml) { // Put all opened tags into an array preg_match_all("#<([a-z][a-z0-9]*)\\b.*?(?!/)>#i", $tmp, $result); $openedTags = $result[1]; // Some tags self close so they do not need a separate close tag. $openedTags = array_diff($openedTags, array("img", "hr", "br")); $openedTags = array_values($openedTags); // Put all closed tags into an array preg_match_all("#</([a-z][a-z0-9]*)\\b(?:[^>]*?)>#iU", $tmp, $result); $closedTags = $result[1]; $numOpened = count($openedTags); // All tags are closed so trim the text and finish. if (count($closedTags) == $numOpened) { return trim($tmp) . '...'; } // Closing tags need to be in the reverse order of opening tags. $openedTags = array_reverse($openedTags); // Close tags for ($i = 0; $i < $numOpened; $i++) { if (!in_array($openedTags[$i], $closedTags)) { $tmp .= "</" . $openedTags[$i] . ">"; } else { unset($closedTags[array_search($openedTags[$i], $closedTags)]); } } } if ($tmp === false || strlen($text) > strlen($tmp)) { $text = trim($tmp) . '...'; } } // Clean up any internal spaces created by the processing. $text = str_replace(' </', '</', $text); $text = str_replace(' ...', '...', $text); return $text; }
function viewlink($link_id, $my, $limitstart, $option) { global $savantConf, $mtconf; $link = loadLink($link_id, $savantConf, $fields, $params); $document =& JFactory::getDocument(); if ($link === false) { if ($mtconf->get('unpublished_message_cfid') > 0) { $database =& JFactory::getDBO(); $database->setQuery('SELECT l.*, u.username AS username FROM #__mt_links AS l ' . 'LEFT JOIN #__users AS u ON u.id = l.user_id ' . 'WHERE link_id = ' . $database->quote($link_id) . ' LIMIT 1'); $link = $database->loadObject(); if ($link->link_published == 0) { $database->setQuery('SELECT value FROM #__mt_cfvalues WHERE link_id = ' . $database->quote($link_id) . ' AND cf_id = ' . $database->quote($mtconf->get('unpublished_message_cfid')) . ' LIMIT 1'); $unpublished_message = $database->loadResult(); if (!empty($unpublished_message)) { $params =& new JParameter($link->attribs); $savant = new Savant2($savantConf); $fields = loadFields($link); assignCommonViewlinkVar($savant, $link, $fields, $pathWay, $params); $unpublished_message_cf = $fields->getFieldById($mtconf->get('unpublished_message_cfid')); $unpublished_message = $unpublished_message_cf->getOutput(); $savant->assign('error_msg', JText::sprintf('This listing has been unpublished for the following reason:', $unpublished_message)); $savant->assign('my', $my); $savant->display('page_errorListing.tpl.php'); } else { JError::raiseError(404, JText::_('Resource Not Found')); } } else { JError::raiseError(404, JText::_('Resource Not Found')); } } else { JError::raiseError(404, JText::_('Resource Not Found')); } } else { # Set Page Title $document->setTitle($link->link_name); # Add META tags if ($mtconf->getjconf('MetaTitle') == '1') { $document->setMetadata('title', htmlspecialchars($link->link_name)); } if ($mtconf->getjconf('MetaAuthor') == '1') { $document->setMetadata('author', htmlspecialchars($link->owner)); } if (!empty($link->metadesc)) { $document->setDescription(htmlspecialchars($link->metadesc)); } elseif (!empty($link->link_desc)) { $metadesc_maxlength = 300; // Get the first 300 characters $metadesc = JString::trim(strip_tags($link->link_desc)); $metadesc = JString::str_ireplace("\r\n", "", $metadesc); $metadesc = JString::substr($metadesc, 0, $metadesc_maxlength); // Make sure the meta description is complete and is not truncated in the middle of a sentence. if (JString::strlen($link->link_desc) > $metadesc_maxlength && substr($metadesc, -1, 1) != '.') { if (strrpos($metadesc, '.') !== false) { $metadesc = JString::substr($metadesc, 0, JString::strrpos($metadesc, '.') + 1); } } $document->setDescription(htmlspecialchars($metadesc)); } if ($link->metakey != '') { $document->setMetaData('keywords', $link->metakey); } $document->addCustomTag(' <script src="' . $mtconf->getjconf('live_site') . $mtconf->get('relative_path_to_js_library') . '" type="text/javascript"></script>'); $document->addCustomTag(' <script src="' . $mtconf->getjconf('live_site') . '/components/com_mtree/js/vote.js" type="text/javascript"></script>'); # Predefine variables: $prevar = " <script type=\"text/javascript\"><!-- \n"; $prevar .= "jQuery.noConflict();\n"; $prevar .= "var mtoken=\"" . JUtility::getToken() . "\";\n"; $prevar .= "var mosConfig_live_site=\"" . $mtconf->getjconf('live_site') . "\";\n"; $prevar .= "var langRateThisListing=\"" . JText::_('Rate this listing', true) . "\";\n"; $prevar .= "var ratingText=new Array();\n"; $prevar .= "ratingText[5]=\"" . JText::_('Rating 5', true) . "\";\n"; $prevar .= "ratingText[4]=\"" . JText::_('Rating 4', true) . "\";\n"; $prevar .= "ratingText[3]=\"" . JText::_('Rating 3', true) . "\";\n"; $prevar .= "ratingText[2]=\"" . JText::_('Rating 2', true) . "\";\n"; $prevar .= "ratingText[1]=\"" . JText::_('Rating 1', true) . "\";\n"; $prevar .= "//--></script>"; $document->addCustomTag($prevar); if (!empty($my->id) && !$mtconf->get('cache_registered_viewlink')) { viewlink_cache($link, $limitstart, $fields, $params, $my, $option); } else { $cache =& JFactory::getCache('com_mtree'); $cache->call('viewlink_cache', $link, $limitstart, $fields, $params, $my, $option); } } }