Skip to content

Instantly share code, notes, and snippets.

@01-Scripts
Last active August 8, 2018 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 01-Scripts/763398 to your computer and use it in GitHub Desktop.
Save 01-Scripts/763398 to your computer and use it in GitHub Desktop.
Artikelteaser für 01-Artikelsystem V3 http://www.01-scripts.de/01article.php
<?PHP
/*
01-Artikelsystem V3 - Copyright 2006-2018 by Michael Lorer - 01-Scripts.de
Lizenz: Creative-Commons: Namensnennung-Keine kommerzielle Nutzung-Weitergabe unter gleichen Bedingungen 3.0 Deutschland
Weitere Lizenzinformationen unter: http://www.01-scripts.de/lizenz.php
Modul: 01article
Dateiinfo: Teaser-Ausgabe
*/
/* !!!!!!!!!!! !!!!!!!!!!!
The configuration variables can be found in line 138ff
Please add your MySQL connection strings and configuration settings there!
!!!!!!!!!!! !!!!!!!!!!!
*/
/**
* truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
* http://alanwhipple.com/2011/05/25/php-truncate-string-preserving-html-tags-words/
*
* @param string $text String to truncate.
* @param integer $length Length of returned string, including ellipsis.
* @param string $ending Ending to be appended to the trimmed string.
* @param boolean $exact If false, $text will not be cut mid-word
* @param boolean $considerHtml If true, HTML tags would be handled correctly
*
* @return string Trimmed string.
*/
if(!function_exists("truncateHtml")){
function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
if ($considerHtml) {
// if the plain text is shorter than the maximum length, return the whole text
if (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 = 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, 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 = 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 += strlen($entity[0]);
} else {
// no more characters left
break;
}
}
}
$truncate .= 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 (strlen($text) <= $length) {
return $text;
} else {
$truncate = substr($text, 0, $length - strlen($ending));
}
}
// if the words shouldn't be cut in the middle...
if (!$exact) {
// ...search the last occurance of a space...
$spacepos = strrpos($truncate, ' ');
if (isset($spacepos)) {
// ...and cut the text in this position
$truncate = substr($truncate, 0, $spacepos);
}
}
// add the defined ending to the text
$truncate .= $ending;
if($considerHtml) {
// close all unclosed html-tags
foreach ($open_tags as $tag) {
$truncate .= '</' . $tag . '>';
}
}
return $truncate;
}
}
if(!function_exists("addP2Link")){
function addP2Link($link,$parameter){
$amp = "&amp;";
if(strchr($link,"?"))
return $link.$amp.$parameter;
else
return $link."?".$parameter;
}
}
if(!function_exists("Teaser4_01Article")){
function Teaser4_01Article(){
// MySQL-Zugangsdaten
$user = "user"; // MySQL-Username
$passw = ""; // MySQL-Passwort
$host = "localhost"; // MySQL-Host
$database = ""; // MySQL-Datenbank
$instnr = "1"; // Installationsnummer des 01ACP
// Modul
$modul = "01article"; // IDname des Moduls, dessen aktuellster Eintrag geteasert ausgegeben werden soll
// Wenn Sie Bilder und Dateianhänge im Teaser anzeigen möchten, geben Sie folgende beiden Pfadangaben ein:
$picuploaddir = ""; // Absoluter Pfad (inkl. http://) zum Verzeichnis 01scripts/01pics/
$attachmentuploaddir = ""; // Absoluter Pfad (inkl. http://) zum Verzeichnis 01scripts/01files/
// Einstellungen
$ziel_url = "http://www.domain.de/index.php"; // Ziel-Adresse unter der das 01-Artikelsystem per PHP eingebunden wurde
$cats = ""; // Nur Artikel aus bestimmten Kategorien ausgeben? (Kategorie-IDs kommasepariert eingeben: z.B. "1,2,7,22" )
$limit = 5; // Wie viele Einträge sollen ausgegegben werden?
$text_len = 150; // Wie viele Zeichen des Eintrags sollen ausgegeben werden?
$use_zusam = FALSE; // Soll ein ggf. hinterlegter Einleitungstext verwendet werden (TRUE) oder der Teaser immer direkt aus dem eigentlichen Artikeltext generiert werden (FALSE)?
$mod_rewrite= FALSE; // Wenn Sie im 01-Artikelsystem die mod_rewrite-Funktion aktiviert haben, können Sie dies hier auch tun (TRUE)
$keep_links = TRUE; // Sollen Links im Text erhalten bleiben oder entfernt werden? (TRUE/FALSE)
$show_pics = FALSE; // Sollen Bilder und Anhänge in den Artikeln anegezeigt werden? (TRUE/FALSE)
$show_cat = FALSE; // Name der Kategorie in der der jew. Artikel eingeordnet ist ausgeben? (TRUE/FALSE)
// Weitere Variablen (müssen nicht geändert werden)
$mysql_tables['module'] = "01_".$instnr."_module";
/* Verbindung zur MySQL-Datenbank aufbauen */
$mysqli = new mysqli($host, $user, $passw, $database);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$list = $mysqli->query("SELECT nr FROM ".$mysql_tables['module']." WHERE idname = '".$mysqli->escape_string($modul)."' LIMIT 1");
while($row = $list->fetch_assoc()){
$module_nr = $row['nr'];
$mysql_tables['artikel'] = "01_".$instnr."_".$row['nr']."_article";
if($show_cat) $mysql_tables['cats'] = "01_".$instnr."_".$row['nr']."_articlecategory";
}
if(isset($mysql_tables['artikel'])){
// MySQL-Query (Kategorien berücksichtigen)
if(isset($cats) && !empty($cats)){
$cids = explode(",",$cats);
$add2query_cat = " 1=2 ";
foreach($cids as $value){
$add2query_cat .= " OR newscatid LIKE '%,".$mysqli->escape_string($value).",%' ";
}
}
else{ $cids = ""; $add2query_cat = "1=1"; }
// Alle Kategorien in einen mehrdimensionalen Array einlesen
if($show_cat){
$listcat = $mysqli->query("SELECT * FROM ".$mysql_tables['cats']." ORDER BY sortid,name");
while($rowcat = $listcat->fetch_assoc()){
$category[$rowcat['id']]['id'] = $rowcat['id'];
$category[$rowcat['id']]['name'] = htmlentities($rowcat['name']);
$category[$rowcat['id']]['catpic'] = $rowcat['catpic'];
}
}
$query = "SELECT id,utimestamp,titel,newscatid,content,autozusammen,zusammenfassung FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND utimestamp<='".time()."' AND (endtime>='".time()."' OR endtime='0') AND (".$add2query_cat.") ORDER BY utimestamp DESC LIMIT ".$mysqli->escape_string($limit)."";
$list = $mysqli->query($query);
while($row = $list->fetch_assoc()){
$datum = date("d.m.y",$row['utimestamp']);
$uhrzeit = date("G:i",$row['utimestamp']);
if($use_zusam && $row['autozusammen'] == 0 && !empty($row['zusammenfassung']))
$text = $row['zusammenfassung'];
else
$text = $row['content'];
$strip = "";
//Links?
if($keep_links)
$strip = "<a>";
// Bilder und Attachments:
if($show_pics){
$text = str_replace("../01pics/",$picuploaddir,$text);
$text = str_replace("../01files/",$attachmentuploaddir,$text);
$strip = "<a><img>";
}
// Kategorien auslesen & auflisten
$catname = "";
if($show_cat && $row['newscatid'] != "0"){
$c = 0;
$newscatids_array = explode(",",substr($row['newscatid'],1,strlen($row['newscatid'])-2));
foreach($newscatids_array as $newscatid_s){
if(isset($category[$newscatid_s]['name'])){
if($c > 0) $catname .= ", ";
$catname .= "<a href=\"".addP2Link($ziel_url,"catid=".$newscatid_s)."\" class=\"catlink\">".$category[$newscatid_s]['name']."</a>";
$c++;
}
}
}
// Mod_Rewrite?
if($mod_rewrite){
// Parse mod_rewrite-Link
$string = strtolower($row['titel']);
$string = str_replace("ä","ae",$string);
$string = str_replace("ö","oe",$string);
$string = str_replace("ü","ue",$string);
$string = str_replace("&auml;","ae",$string);
$string = str_replace("&ouml;","oe",$string);
$string = str_replace("&uuml;","ue",$string);
$string = str_replace("&amp;","und",$string);
$string = str_replace(" ","-",$string);
$string = str_replace(",","_",$string);
$string = str_replace("ß","ss",$string);
$string = rawurlencode($string);
$url = parse_url($ziel_url);
$link = $url['scheme']."://".$url['host']."/".$string.",".$module_nr.",".$row['id'].".html#01id".$row['id'];
}else{
$link = addP2Link($ziel_url,"artid=".$row['id']."#01id".$row['id']."");
}
// Ausgabe beginnt:
echo "<div class=\"teaser\">";
echo "<a href=\"".$link."\" class=\"title\">".$row['titel']."</a><br />\n";
if(!empty($catname)) echo "<span class=\"catlink\">Kategorie: ".$catname."</span><br />\n";
echo "<span class=\"datetime\">".$datum.", ".$uhrzeit." Uhr</span><br /><br />\n";
echo trim(truncateHtml(strip_tags($text,$strip), $text_len));
echo "<br /></div>";
}
}
else
echo "<b>Fehler:</b> Modul-Tabelle konnte nicht geladen werden.
Bitte überprüfen Sie die Konfiguration";
}
}
Teaser4_01Article();
?>
@01-Scripts
Copy link
Author

Neue Version unterstützt unter anderem

  • Kategorie-Filter
  • Kategorien anzeigen oder nicht
  • Links und/oder Bilder anzeigen
  • Verbesserter Textlängen-Umbruch
  • mod_rewrite-Unterstützung

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment