<?php
/* ====================
[BEGIN_COT_EXT]
Hooks=global
[END_COT_EXT]
==================== */

defined('COT_CODE') or die('Wrong URL');

// Calculate editor timestamp
if (!function_exists('ckeditor_max_timestamp'))
{
  function ckeditor_max_timestamp($dir)
  {
    $maxtime = 0;
    $dp = opendir($dir);
    while ($f = readdir($dp))
    {
      if ($f[0] != '.')
      {
        $fname = $dir . '/' . $f;
        if (is_dir($fname))
          $mtime = ckeditor_max_timestamp($fname);
        else
          $mtime = filemtime($fname);

        if ($mtime > $maxtime)
          $maxtime = $mtime;
        }
      }
    closedir($dp);
    return $maxtime;
  }
}

// Calculate editor timestamp
if (!function_exists('ckeditor_init'))
{
  function ckeditor_init($preset = 'default', $init = true)
  {
    global $ckeditor_timestamp, $cfg, $usr;

    $return = '';

    if (!$ckeditor_timestamp)
      $ckeditor_timestamp = ckeditor_max_timestamp($cfg['plugins_dir'] . '/ckeditor/lib');

    // Main CKEditor file
    $return .= '<script type="text/javascript" src="' . $cfg['plugins_dir'] . '/ckeditor/lib/ckeditor.js?'.$ckeditor_timestamp.'"></script>';

    if($preset != 'default' && file_exists($cfg['plugins_dir'] . "/ckeditor/presets/ckeditor.$preset.set.js"))
    {
      $preset_name = $preset;
    }
    elseif ($usr['id'] > 0)
    {
      $preset_name = 'group_' . $usr['maingrp'];
      if (!file_exists($cfg['plugins_dir'] . "/ckeditor/presets/ckeditor.$preset_name.set.js"))
      {
        $preset_name = 'default';
      }
    }
    else
    {
      $preset_name = file_exists($cfg['plugins_dir'] . "/ckeditor/presets/ckeditor.group_1.set.js") ? 'group_1' : 'default';
    }
    $return .= '<script type="text/javascript" src="' . $cfg['plugins_dir'] . '/ckeditor/presets/ckeditor.'.$preset_name.'.set.js?'.$ckeditor_timestamp.'"></script>';

    $return .= '<script type="text/javascript">
                  //<![CDATA[
                  CKEDITOR.timestamp = '.$ckeditor_timestamp.';
                  //]]>
                </script>';

    return $return;
  }
}
