<?php
$server_host = $_SERVER['HTTP_HOST'];
if(str_ireplace('www.', '', $server_host) != str_replace('www.', '', $ultra_domainname)) {
	$server_host .= "/$ultra_addonname";
}

// Load the required JS and/or CSS
//--//$optres['js'][] = "$path" . "js/dimensions.js";
//--//$optres['js'][] = "$path" . "js/jquery-ui.custom.js";
//--//$optres['css'][] = "$path" . "css/jqModal.css";
//--//$optres['js'][] = "$path" . "js/jqModal.js";

$show_icons = (isset($module_show_icons) && intval($module_show_icons) == 1) ? true : false;
$show_expander = (isset($module_show_expander) && intval($module_show_expander) == 1) ? true : false;

if(!function_exists("show_article_breadcrumbs")) {
	function show_article_breadcrumbs($parent_id){
		$display_bread = false;
		$ret = array();
		$newparent = $parent_id;
		$root = $newparent;
		$i=0;
		$go_up = true;
		$query = "SELECT * FROM main_article_categ WHERE cat_id = '$parent_id'";
		$res = mysql_query ($query);
		$line = mysql_fetch_array($res);
		${"root$i"}=$line["title_en"];
		${"friendly$i"}=$line["friendly_url"];
		${"link$i"}=$line["cat_id"];
		if($line['is_root'] == 1) {
			$go_up = false;
			$display_bread = true;
		}
		while($go_up && $root>0){
			$newparent=$line["parent_id"];
			$query = "SELECT * FROM  main_article_categ WHERE cat_id = '$newparent'";
			$result = mysql_query ($query);
			$line = mysql_fetch_array($result);
			$i++;
			${"root$i"}=$line["title_en"];
			${"friendly$i"}=$line["friendly_url"];
			${"link$i"}=$line["cat_id"];
			$root=$newparent;
			
			if($line['is_root'] == 1) {
				$display_bread = true;
				${"root$i"} = "[home]" . stripslashes(trim($line["title_en"]));
				$go_up = false;
			}
		}
		for($j=$i;$j>=0; $j = $j-1){
			if($j>=0){
				//if($j != $i) $ret .= '<strong> &raquo; </strong>';
				$class= "blue";
				if(strpos(${"root$j"},"[home]") !== false) {
					${"root$j"} = str_replace("[home]", "", ${"root$j"});
					$class = "blue_home";
				}
				
				//$ret .= '<a href="articles/'.${"friendly$j"} . ".html" .'" class="' . $class . '">' . ${"root$j"} . '</a>';
                $ret[] = array(
                    "link"  => 'articles/' . ${"friendly$j"} . '.html',
                    "title" => ${"root$j"}
                );
			}
			
		}
		
		if($display_bread) return $ret;
		else return false;
	}
}

function categGetSubs($cat_id) {
	$ret = array();
	$q = "select * from main_article_categ where parent_id='$cat_id' and active='yes' order by order_seq asc;";
	$r = @mysql_query($q);
	if($r && mysql_num_rows($r)>0) {
		while ($row = mysql_fetch_assoc($r)) {
			$ret [] = array(
				"categ_id" 					=> intval($row['cat_id']),
				"categ_title" 				=> trim(stripslashes($row["title_en"])),
				"categ_friendly_url" 		=> trim(stripslashes($row["friendly_url"])),
				"categ_url"					=> str_replace("http://", "", trim(stripslashes($row['url']))),
				"categ_blank" 				=> trim($row['_blank']),
				"categ_parent_id"			=> intval($row['parent_id']),
				"small_logo"				=> trim($row['small_logo']),
				"abstract"					=> trim(stripslashes($row['short_desc_en'])),
				"content_type"				=> ($row['content_type'] != "") ? $row['content_type'] : "article"
			);
		}
	}
	
	if(count($ret)) return $ret;
	
	return false;
}

function categDisplaySubs($ar, $level=-1, $max_level=10, $to_show_icons=true) {
	
	$show_icons = ($to_show_icons == true) ? 'null' : 'false';
	$cur_level = 0;
	$sub_level = 0;
	$class_level = "";
	if($level >= 0) {
		$class_level = "level_" . $level;
		$cur_level = $level;
		$sub_level = $cur_level + 1;
	}
	if(!is_array($ar) || count($ar) == 0) return false;
	foreach ($ar as $i=>$categ) {
		$disp_url = ($categ['categ_url'] != "") ? ("http://" . str_ireplace("http://", "", trim($categ['categ_url']))) : ('articles/' . $categ['categ_friendly_url'] . ".html");
		$disp_target = ($categ['categ_blank'] == "yes") ? '_blank' : '_self';
		$disp_node = "node_" . $categ['categ_id'];
		$disp_title = mysql_real_escape_string($categ['categ_title']);
		$abstract = $categ['abstract'];
		
		$disp_li = '<li>';
		$disp_li .= '<h2><a href="'. $disp_url .'" target="'. $disp_target.'" title="'. $disp_title.'" class="article_folder">'. $disp_title. '</a></h2>';
		if($abstract != "") {
			$disp_li .= '<div class="categ_abstract"><p>' . $abstract . '</p><div style="clear: both;"></div></div>';
		}
		
		//$order_by = ($categ['content_type'] == "news") ? "created desc" : "order_seq asc";
		
		
		$subs = categGetSubs($categ['categ_id']);
		if($subs && count($subs)) {
			//$disp_li = str_replace("jstree-closed", "jstree-open", $disp_li);
			echo $disp_li;
			if($max_level > 0) {
				echo '<ul>';
				categDisplaySubs($subs, $sub_level, $max_level-1, $to_show_icons);
				echo '</ul>';
			}
			else {
				echo '<ul>';
				categDisplaySubs($subs, $sub_level, $max_level-1, $to_show_icons);
				echo '</ul>';
			}
			echo '</li>';
			
			$arts = categGetArticles($categ['categ_id'], ($categ['content_type'] != "") ? $categ['content_type'] : "article");
			if($arts) {
				categDisplayArticles($arts, $cur_level, $to_show_icons);
			}
			
		}
		else {
			$arts = categGetArticles($categ['categ_id'], ($categ['content_type'] != "" ? $categ['content_type'] : "article"));
			if($arts) {
				
				//$disp_li = str_replace('class="folder"', 'class="lazy folder"', $disp_li);
				//$disp_li = str_replace('expand:true', 'expand:false', $disp_li);
				echo $disp_li;
				echo '<ul class="sub_arts">';
				categDisplayArticles($arts, $cur_level, $to_show_icons);
				echo '</ul>';
				echo '</li>';
			}
			
			
		}
		
		
	}
}

function categGetArticles($cat_id, $content_type="article") {
	$order_by='order_seq asc';
	
	if($content_type == "news") {
		$order_by='created desc';
	}
	
	$ret = array();
	$q = "select * from main_article where parent_id='$cat_id' and active='yes' order by $order_by;";
	
	if(isset($_REQUEST['debug1'])) {
		echo "<br/>$q";
	}
	
	$r = @mysql_query($q);
	if($r && mysql_num_rows($r)>0) {
		while ($row = mysql_fetch_assoc($r)) {
			$ret [] = array(
				"article_id" 				=> intval($row['article_id']),
				"article_title" 			=> trim(stripslashes($row["title_en"])),
				"article_friendly_url" 		=> trim(stripslashes($row["friendly_url"])),
				"article_url"				=> str_replace("http://", "", trim(stripslashes($row['url']))),
				"article_blank" 			=> trim($row['_blank']),
				"article_parent_id"			=> intval($row['parent_id']),
				"small_photo"				=> $row['small_photo'],
				"body"					    => $row['description_en'],
				"abstract"					=> $row['short_descr_en'],
				"content_type"				=> $content_type,
				"created"					=> $row['created'],	
				"updated"					=> $row['updated']
			);
		}
	}
	
	if(count($ret)) return $ret;
	
	return false;
}


function categDisplayArticles($ar, $level=-1, $to_show_icons=true) {
	global $full_uri, $full_addon_uri, $server_host, $domain_id;
	$show_icons = ($to_show_icons == true) ? 'null' : 'false';
	$class_level = "level_article";
    $titles = array();
	//if($level >= 0) {
	//	$class_level = "level_" . $level;
	//}

	if(!is_array($ar) || count($ar) == 0) return false;
	foreach ($ar as $i=>$article) {
		$disp_url = ($article['article_url'] != "") ? ("http://" . $article['article_url']) : "";
		$disp_href = "article/" . $article['article_friendly_url'] . ".html";
		
		$href = $disp_url != "" ? $disp_url : $disp_href;
		
		$disp_target = ($article['article_blank'] == "yes") ? '_blank' : '_self';
        $disp_rel = $disp_target == '_blank' ? 'noopener' : '';
        $disp_rel = trim($disp_rel) != "" ? ' rel="' . $disp_rel . '"' : '';
		$disp_node = "";
		$disp_title = $article['article_title'];
        $titles [] = $disp_title;
		
		$datetime = "";
		if($article['content_type'] == "news") {
			
			$orig_timezone = date_default_timezone_get();
			date_default_timezone_set("UTC");
			$created_timestamp = strtotime($article['created']);
			$created = date("Y-m-d\TH:i:s", $created_timestamp);
			//$created_str = date("d/m/Y H:i", $created_timestamp);
            $created_str = date("l, j F Y h:i A", $created_timestamp);
			date_default_timezone_set($orig_timezone);
			
			//$datetime = '<time datetime="'.date("Y-m-d", strtotime($article['created'])).'" pubdate="">['.date("d/m/Y", strtotime($article['created'])).']</time> ';
			$datetime = '<div class="news-date"><i class="fa fa-clock-o"></i> <meta itemprop="datePublished" content="'.date('c', $created_timestamp).'"><time datetime="'.$created.'" pubdate="">'.$created_str.'</time></div>';
		}
		
		//echo '<li>';
		?>
		<div class="list-group-item no-border-lr" itemscope="itemscope" itemtype="http://schema.org/<?php echo ($article['content_type'] == "news") ? 'NewsArticle' : 'Article';?>">
			<?php
            if(isset($_SESSION['user_id']) && intval($_SESSION['user_id']) > 0) {
                echo '<div class="user-action-container"><a class="user-action-inline" href="/admin/index.php?plugin=contents&action=article&article_id='.$article['article_id'].'" target="_blank">Edit</a></div>';
            }
            echo '<a href="' . ($disp_url == "" ? $full_addon_uri . $disp_href : $disp_url) . '" target="' . $disp_target . '" '.$disp_rel.' title="' . $disp_title . '" class="article-url" itemprop="url"><span itemprop="name">' . $disp_title . '</span></a>';
			$have_photo = false;
			$have_abstract = ($article['abstract'] != "") ? true : false;
			if($article['small_photo'] != "") {
				$article_photo_path = "images/articles/" . $domain_id . '/' . $article['article_id'] . "/" .$article['small_photo'];
				$article_photo_path_th = "images/articles/" . $domain_id . '/' . $article['article_id'] . "/thumbs/" .$article['small_photo'];
				$article_photo = $server_host . "/$article_photo_path";
				$article_photo_th = dirname(__FILE__) . "/../../$article_photo_path_th";

				if(file_exists($article_photo_th)) {
					$have_photo = true;
				}

                //echo $article_photo;
			}

            if(!$have_abstract) {
                $abstract_text = trim(strip_tags($article['body']));
                if(mb_strlen($abstract_text) >= 200) {
                    $article['abstract'] = mb_substr($abstract_text, 0, strpos($abstract_text, '.', 200)) . '.';
                }
                else {
                    $article['abstract'] = $abstract_text;
                }
                $have_abstract = true;
            }


			if($have_abstract) {
				?>
				<div class="article-abstract clearfix" itemprop="headline">
					<?php
					if($have_photo) {
						//echo $article_photo;
						?>
                        <meta itemprop="image" content="http://<?php echo $_SERVER['HTTP_HOST'] . "/$article_photo_path"; ?>">
						<img src="http://<?php echo $_SERVER['HTTP_HOST'] . "/$article_photo_path_th"; ?>" alt="<?php echo $disp_title; ?>" itemprop="image" class="pull-left img-thumbnail img-responsive">
						<?php
					}
					
					echo '<p>' . $article['abstract'] . '</p>';
					?>
				</div>
				<?php
			}

			
			echo $datetime;
			
			?>
		</div>
		
		<?php
		//echo '</li>';
	}
}


/* Social Media plugin **********/
/*$sm_class_overload = "sm-categ";
include(dirname(__FILE__) . "/../sm/sm.php");*/
/***************************/

include_once("$general_path" . "functions.php");
$query = "SELECT * FROM main_article_categ WHERE cat_id='$middle_parent_id'";
//echo $query;
$result = mysql_query ($query);
if($result && mysql_num_rows($result) > 0) {
	$line = mysql_fetch_assoc($result);
	
	$category_title = trim(stripslashes($line['title_en']));
	$category_abstract = trim(stripslashes($line['short_desc_en']));
	$category_meta_description = trim(stripslashes($line['meta_description_en']));
	$category_meta_keywords = trim(stripslashes($line['meta_keywords_en']));
	$category_friendly_url = trim($line['friendly_url']);
	$category_is_root = intval($line['is_root']);
	
	$meta_from_content = array();
	
	
	?>
	<?php
	if($category_is_root != 1) {
		$breads = show_article_breadcrumbs($line['cat_id']);
        if($breads && count($breads) > 0) {
            foreach($breads as $bread) {
                $breadcrumbs [] = $bread;
            }
        }

	}
	?>
	<article class="article cyprus">
		<?php
        if(isset($_SESSION['user_id']) && intval($_SESSION['user_id']) > 0) {
            echo '<div class="user-action-container"><a class="user-action-inline" href="/admin/index.php?plugin=contents&action=article_categ&cat_id='.$line['cat_id'].'" target="_blank">Edit</a></div>';
        }

		$title_on = false;
		if(isset($module_show_parent_title) && $module_show_parent_title == 1 && $category_is_root == 1) {
			?>
			<header>
					<?php
						if($line['url'] != "") {
							$ahref = return_friendly_link('main_article_categ', $line["cat_id"], $line['_blank'], $line['url']);
							?>
							<a class="article_list_middle_main" href="<?php echo $ahref['link'];?>" target="<?php echo $ahref['target'];?>"><?php echo $line["title_en"];?></a>
							<?php
						}
						else {
							echo "<h1>".$line["title_en"]."</h1>";
                            echo '<!--[/SocialShareButtons/]-->';
						}
						
						$title_on = true;
					?>
			</header>
			<?php
		}
		else {
			if(str_replace("/" . $category_friendly_url.'.html', '', $_SERVER['REQUEST_URI']) != $_SERVER['REQUEST_URI']) {
				?>
				<header>
						<?php
							if($line['url'] != "") {
								$ahref = return_friendly_link('main_article_categ', $line["cat_id"], $line['_blank'], $line['url']);
								?>
								<a class="article_list_middle_main" href="<?php echo $ahref['link'];?>" target="<?php echo $ahref['target'];?>"><?php echo $line["title_en"];?></a>
								<?php
							}
							else {
								echo "<h1>".$line["title_en"]."</h1>";
                                echo '<!--[/SocialShareButtons/]-->';
							}
							$title_on = true;
						?>
				</header>
				<?php
			}
			else {
				?>
				<header>
						<?php
							if($line['url'] != "") {
								$ahref = return_friendly_link('main_article_categ', $line["cat_id"], $line['_blank'], $line['url']);
								?>
								<a class="article_list_middle_main" href="<?php echo $ahref['link'];?>" target="<?php echo $ahref['target'];?>"><?php echo $line["title_en"];?></a>
								<?php
							}
							else {
								echo "<h2>".$line["title_en"]."</h2>"; 
							}
							$title_on = true;
						?>
				</header>
				<?php
			}
		}

		$nr_sub_categs = 0;
		$q = "SELECT * FROM main_article_categ WHERE parent_id='$middle_parent_id' and active='yes'";
		$sub_categs = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
		if($sub_categs && mysql_num_rows($sub_categs)>0) {
			$nr_sub_categs = mysql_num_rows($sub_categs);
		}
		
		$root_nodes = array();
		
		if($nr_sub_categs > 0) {
			while ($categ = mysql_fetch_assoc($sub_categs)) {
				$categ_title = trim(stripslashes($categ["title_en"]));
				$categ_friendly_url = trim($categ['friendly_url']);
				$categ_id = $categ['cat_id'];
				$categ_url = (trim($categ['url']) != "") ? "http://" . str_replace("http://", "", trim($categ['url'])) : '';
				$categ_blank = trim($categ['_blank']);
				$categ_short_desc = trim(stripslashes($categ["short_desc_en"]));
				$content_type = trim($categ['content_type']) != "" ? $categ['content_type'] : "article";

                $categ_link = $categ_url != "" ? $categ_url : 'articles/' . $categ_friendly_url . '.html';

				$root_nodes [$categ_id] = "root_" . $categ_id;
				
				$have_list = false;
				$subs = categGetSubs($categ_id);
				$arts = categGetArticles($categ_id, $content_type);
				
				//echo '<pre>', var_export($subs, true), '</pre>';
				//echo '<pre>', var_export($arts, true), '</pre>';
				
				if($subs || $arts) $have_list = true;
				
				if($have_list) {
					
					if(is_array($subs) && count($subs) > 0) {
						foreach ($subs as $i=>$sub_categ) {
							$meta_from_content [] = $sub_categ['categ_title']; 
						}
					}
					
					if(is_array($arts) && count($arts) > 0) {
						foreach ($arts as $i=>$sub_art) {
							$meta_from_content [] = $sub_art['article_title']; 
						}
					}

                    //echo '<pre>', var_export($line, true), '</pre>';

					if($line['is_root'] != 1 && $title_on == false) {
						?>
						<header>
								<?php
									if($line['url'] != "") {
										$ahref = return_friendly_link('main_article_categ', $line["cat_id"], $line['_blank'], $line['url']);
										?>
										<a class="article_list_middle_main" href="<?php echo $ahref['link'];?>" target="<?php echo $ahref['target'];?>"><?php echo $line["title_en"];?></a>
										<?php
									}
									else {
										echo "<h1>".$line["title_en"]."</h1>";
                                        echo '<!--[/SocialShareButtons/]-->';
									}
								?>
						</header>
						<?php 
					}
					?>
					<section class="box box-primary">
                        <header class="box-header">
                            <h2><a href="<?=$categ_link?>"><?=$categ_title;?></a></h2>
                        </header>

						<?php
						if($line['is_root'] != 1) {

							if($categ_short_desc != "") {
								?>
                                <div class="box-body"><p class="categ_abstract"><?php echo $categ_short_desc;?></p></div>
								<?php
							}
						}
						else {
							if($module_show_parent_title == 1) {

								if($categ_short_desc != "") {
									?>
                                    <div class="box-body"><p class="categ_abstract"><?php echo $categ_short_desc;?></p></div>
									<?php
								}
							}
						}
						?>

						<?php
							if(is_array($subs)) {
								//echo '<div id="root_',$categ_id, '" class="sub_article_tree">';
                                echo '<div class="list-group">';
								categDisplaySubs($subs, 0, 10, $show_icons);
								if(is_array($arts)) {
									categDisplayArticles($arts, 0, $show_icons);
								}
								echo '</div>';
                                //echo '</div>';
							}
							else {
                                //echo '<div id="root_',$categ_id, '" class="sub_article_tree">';
                                echo '<div class="list-group">';
								categDisplayArticles($arts, 0, $show_icons);
                                echo '</div>';
                                //echo '</div>';
							}
						?>
					</section>
					<?php
				}
			}
		}
		else {
			
			$q_categ = "SELECT * FROM main_article_categ WHERE cat_id='$middle_parent_id' and active='yes';";
			//echo $q_categ;
			
			$r_categ = mysql_query($q_categ) or die("<strong>$q_categ</strong>".mysql_error());
			if($r_categ && mysql_num_rows($r_categ) >0 ) {
				$row_categ = mysql_fetch_assoc($r_categ);
                $categ_short_desc = trim(stripslashes($row_categ["short_desc_en"]));
                $category_friendly_url = $row_categ["friendly_url"];

                $category_title = trim(stripslashes($line['title_en']));
                $category_abstract = trim(stripslashes($line['short_desc_en']));
                $category_meta_description = trim(stripslashes($line['meta_description_en']));
                $category_meta_keywords = trim(stripslashes($line['meta_keywords_en']));

				
				$arts = categGetArticles($middle_parent_id, ($row_categ['content_type'] != "" ? $row_categ['content_type'] : "article"));
				
				//echo '<pre>', var_export($arts, true), '</pre>';
				
				if(is_array($arts) && count($arts)>0) {
                    foreach($arts as $art) {
                        $meta_from_content [] = $art['article_title'];
                    }
					?>
					<div class="article-body cyprus">
                        <?php
                        if($categ_short_desc != "") {
                            ?>
                            <div><?=$categ_short_desc;?></div>
                            <?php
                        }
                        ?>
						<div id="root_<?=$middle_parent_id?>" class="sub_article_tree">
                            <div class="list-group flat">
                                <?php

                                categDisplayArticles($arts, 0, $show_icons);
                                ?>

						    </div>
                        </div>
					</div>
					<?php
				}
				
			}
			
			
		}
		?>
	</article>
	<?php

	if(str_replace("/" . $category_friendly_url.'.html', '', $_SERVER['REQUEST_URI']) != $_SERVER['REQUEST_URI']) {
		$webpage_title_en = $category_title;
		
		if($category_meta_description != "") {
			$meta['description'] = $category_meta_description;
		}
		elseif ($category_abstract != "" && $line['use_meta'] == 1) {
			$meta['description'] = mb_substr(fix_stripped_words($category_abstract), 0, 150, 'UTF-8');
		}
		elseif (count($meta_from_content) > 0) {
			$meta['description'] = mb_substr($category_title . " | " . implode(", ", $meta_from_content), 0, 150, 'UTF-8');
		}
        else {
            $meta['description'] = $category_title;
        }
		
		if($category_meta_keywords != "") {
			$meta['keywords'] = $category_meta_keywords;
		}
		else {
			$meta['keywords'] = trim($category_title . ', ' . implode(", ", $meta_from_content));
			$meta['keywords'] = rtrim(mb_substr($meta['keywords'], 0, 400, 'UTF-8'), ',');
		}
	}
	
}
?>