Priority File Manager

📁 public_html
Base Directory:
/home/ecedu/public_html/cce/Models
NameTypeSizeActions
📁 .. Folder -
📄 BasicManager.php File 2087
Edit Download
📄 DB.php File 939
Edit Download
📄 DetailsManager.php File 4312
Edit Download
📄 DeviceAuth.php File 698
Edit Download
📄 Functions.php File 8554
Edit Download
📄 ImageManager.php File 2862
Edit Download
📄 News.php File 13517
Edit Download
📄 NewsModel.php File 9228
Edit Download

View File: Functions.php

<?php
declare(strict_types=1);

class Functions
{
    protected bool $editMode = false;

    public function __construct()
    {
        // لا حاجة لكتلة try/catch فارغة
    }
     
    /**
     * الاستعلام عن وضع التحرير
     */
    public function isLogined(): bool
    {
    // --- Authentication & Session Timeout ---
      if (empty($_SESSION['user']) || 
          empty($_SESSION['timeout']) || 
          time() > (int)$_SESSION['timeout']) { 
        return false;
       } 
        return true;
    }

    /**
     * تنظيف المحتوى من الـ HTML مع الحفاظ على فواصل الأسطر
     */
    public function cleanContent(string $content): string
    {
        $content = nl2br($content);
        $content = preg_replace('#(?:<br\s*/?>\s*?){2,}#', ' ', $content);
        return trim(strip_tags($content));
    }
    
    public function htmlToText(string $content): string
    { 
        return trim(strip_tags($content));
    }

    /**
     * إزالة وسوم معينة من HTML لكن ترك الباقي مصقولاً
     */
    public function cleanHtml(string $content): string
    {
        return trim(preg_replace(
            '/<\/?(figure|table|tbody|thead|tr|td)([^>]*)>/i',
            '',
            $content
        ));
    }

    function sanitizeHtml(string $html): string
    {
    // قائمة الوسوم المسموحة
    $allowedTags = '<p><br><strong><b><i><em><ul><ol><li><h1><h2><h3><h4><h5><h6><blockquote><a><img>';

    // إزالة الوسوم غير المسموحة
    $cleaned = strip_tags($html, $allowedTags);

    // استخدام DOMDocument لحذف سمات غير مرغوبة مثل onclick أو style
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);

    $doc->loadHTML(mb_convert_encoding($cleaned, 'HTML-ENTITIES', 'UTF-8'));
    libxml_clear_errors();

    $xpath = new DOMXPath($doc);

    // حذف السمات الخطيرة من كل العناصر
    foreach ($xpath->query('//@*') as $attr) {
        $attrName = strtolower($attr->nodeName);
        if (in_array($attrName, ['onclick', 'onerror', 'onload', 'style'])) {
            $attr->ownerElement->removeAttribute($attr->nodeName);
        }
    }

    // استخراج فقط محتوى <body> بدون <html><body> التغليف
    $body = $doc->getElementsByTagName('body')->item(0);
    $cleanHtml = '';
    foreach ($body->childNodes as $child) {
        $cleanHtml .= $doc->saveHTML($child);
    }

    return trim($cleanHtml);
}

    /**
     * إرجاع تاريخ بصيغة <time> مع اسم اليوم والشهر حسب اللغة
     */
    public function getDate(string $lang = 'ar'): string
    {
        $months = [
            'ar' => ['كانون الثاني','شباط','آذار','نيسان','أيار','حزيران','تموز','آب','أيلول','تشرين الأول','تشرين الثاني','كانون الأول'],
            'ku' => ['کانونی دووەم','شوبات','ئازار','نیسان','ئایار','حزیران','تەمووز','ئاب','ئەیلول','تشرینی یەکەم','تشرینی دووەم','کانونی یەکەم'],
            'en' => ['January','February','March','April','May','June','July','August','September','October','November','December'],
        ];
        $days = [
            'ar' => ['الأحد','الاثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت'],
            'ku' => ['یەکشەممە','دووشەممە','سێشەممە','چوارشەممە','پێنجشەممە','هەینی','شەممە'],
            'en' => ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        ];

        if (!isset($months[$lang])) {
            $lang = 'ar';
        }

        $w       = (int) date('w');      // 0 = الأحد
        $d       = (int) date('d');
        $m       = (int) date('n') - 1;  // 0-11
        $y       = (int) date('Y');
        $isoDate = date('Y-m-d');

        return sprintf(
            '<time class="navbar-text me-2" datetime="%s">%s %d, %s, %d</time>',
            $isoDate,
            $days[$lang][$w],
            $d,
            $months[$lang][$m],
            $y
        );
    }

    /**
     * اقتطاع جزء من النص من موضع بداية f حتى t
     */
    public function subText(string $body, int $from, int $to): string
    {
        $length = $to - $from;
        if (mb_strlen($body) <= $length) {
            return $this->cleanContent($body);
        }

        $snippet = mb_substr($body, $from, $length);
        $lastPos = mb_strrpos($snippet, ' ');
        if ($lastPos !== false) {
            $snippet = mb_substr($snippet, 0, $lastPos);
        }

        return $this->cleanContent($snippet) . ' ...';
    }


     
    public function cleanNewHtml(string $html): string
    {
      if (empty($html)) {
        return '';
      }
    
      $allowedTags = '<p><br><div><span><strong><b><em><i><u><ul><ol><li><a><img><blockquote><code><pre><h1><h2><h3><h4><h5><h6>';
    
      $cleanHtml = strip_tags($html, $allowedTags);
      $cleanHtml = html_entity_decode($cleanHtml, ENT_QUOTES, 'UTF-8');
      $cleanHtml = str_replace(['&nbsp;', '&#160;'], ' ', $cleanHtml);
      $cleanHtml = preg_replace('/(<[^>]+)\s+on\w+\s*=[^>]*>/i', '$1>', $cleanHtml);
      $cleanHtml = preg_replace('/\s+/', ' ', $cleanHtml);
    
       return trim($cleanHtml);
    }

     public function subHtmlText(string $html, int $from, int $to): string
     {
      $limit = $to - $from;
      $result = '';
      $openTags = [];
      $currentLength = 0;
      $html=  $this-> cleanNewHtml($html);
      preg_match_all('/<[^>]+>|[^<]+/u', $html, $parts, PREG_SET_ORDER);

      foreach ($parts as $part) {
        $content = $part[0];
        
        if ($content[0] === '<') {
            // معالجة الوسوم
            if (!str_starts_with($content, '</')) {
                preg_match('/^<([a-z0-9]+)/i', $content, $tag);
                if ($tag) $openTags[] = $tag[1];
            } else {
                preg_match('/^<\/([a-z0-9]+)/i', $content, $tag);
                if ($tag) array_pop($openTags);
            }
            $result .= $content;
        } else {
            // معالجة النص
            $remaining = $limit - $currentLength;
            if ($remaining <= 0) break;
            
            $truncated = mb_substr($content, 0, $remaining);
            $result .= $truncated;
            $currentLength += mb_strlen($truncated);
        }
      }

      // إغلاق الوسوم المفتوحة
      while (!empty($openTags)) {
        $result .= '</' . array_pop($openTags) . '>';
      }

      return $result . ($currentLength >= $limit ? ' ...' : '');
     }

 

    /**
     * بناء مسار صورة معروف الامتداد
     */
    public function getPath(string $basePath, int $newsId, string $extension): string
    {
        return rtrim($basePath, DIRECTORY_SEPARATOR)
            . DIRECTORY_SEPARATOR
            . "img_{$newsId}." . ltrim($extension, '.');
    }

    /**
     * البحث عن أول ملف صورة لأي امتداد
     */
    public function findImagePath(string $basePath, int $newsId): ?string
    {
        $pattern = rtrim($basePath, DIRECTORY_SEPARATOR)
            . DIRECTORY_SEPARATOR
            . "img_{$newsId}.*";
        $files = glob($pattern);
        return $files[0] ?? null;
    }

    /**
     * رابط "عرض المزيد" مع نص متعدد اللغات
     */
    public function forDetails(int $id, string $lang = 'ar'): string
    {
        $texts = [
            'ar' => 'عرض المزيد ..',
            'ku' => 'زیاتر ببینە ..',
            'en' => 'Read more ..',
        ];
        $text = $texts[$lang] ?? $texts['ar'];
        $url  = 'listnews.php?i=' . $id;

        return sprintf(
            '<span class="detail-link">&emsp;<i><a href="%s">%s</a></i></span>',
            $url,
            $text
        );
    }
    
    public function getNewsOptions($newsData)
    {

        $html = '';
        $cont = count($newsData);
        for ($x = 0; $x < $cont; $x++) {
            $fld1 = $newsData[$x]["news_id"];
            $fld2 = $newsData[$x]["news_title"];
            $html .= "<option value=" . $fld1 . ">" . $fld2 . "</option>";
        }

        return $html;
    }
     
    public function getDetailsLink(int $id): string
    {
        return 'listnews.php?i=' . $id;
    }
}