Ejemplo n.º 1
0
function entities_to_7bit($str)
{
    require_once LEPTON_PATH . '/framework/summary.utf8.php';
    // convert to UTF-8
    $str = charset_to_utf8($str);
    if (!utf8_check($str)) {
        return $str;
    }
    // replace some specials
    $str = utf8_stripspecials($str, '_');
    // translate non-ASCII characters to ASCII
    $str = utf8_romanize($str);
    // missed some? - Many UTF-8-chars can't be romanized
    // convert to HTML-entities, and replace entites by hex-numbers
    $str = utf8_fast_umlauts_to_entities($str, false);
    $str = str_replace(''', ''', $str);
    //    $str = preg_replace_callback('/&#([0-9]+);/', function($matches) {return "dechex($matches[1])";}, $str);
    //    $str = preg_replace_callback('/&#([0-9]+);/', function($matches) {return dechex($matches[1]);}, $str);
    if (version_compare(PHP_VERSION, '5.3', '<')) {
        $str = preg_replace('/&#([0-9]+);/e', "dechex('\$1')", $str);
    } else {
        $str = preg_replace_callback('/&#([0-9]+);/', create_function('$aMatches', 'return dechex($aMatches[1]);'), $str);
    }
    // maybe there are some &gt; &lt; &apos; &quot; &amp; &nbsp; left, replace them too
    $str = str_replace(array('&gt;', '&lt;', '&apos;', '\'', '&quot;', '&amp;'), '', $str);
    $str = str_replace('&amp;', '', $str);
    return $str;
}
Ejemplo n.º 2
0
 /**
  * Constructor
  */
 public function __construct()
 {
     global $INPUT;
     parent::__construct();
     // ldap extension is needed
     if (!function_exists('ldap_connect')) {
         $this->_debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
         $this->success = false;
         return;
     }
     // Prepare SSO
     if (!empty($_SERVER['REMOTE_USER'])) {
         // make sure the right encoding is used
         if ($this->getConf('sso_charset')) {
             $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
         } elseif (!utf8_check($_SERVER['REMOTE_USER'])) {
             $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
         }
         // trust the incoming user
         if ($this->conf['sso']) {
             $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
             // we need to simulate a login
             if (empty($_COOKIE[DOKU_COOKIE])) {
                 $INPUT->set('u', $_SERVER['REMOTE_USER']);
                 $INPUT->set('p', 'sso_only');
             }
         }
     }
     // Add the capabilities to change the password
     $this->cando['modPass'] = $this->getConf('modPass');
 }
Ejemplo n.º 3
0
 /**
  * Constructor
  */
 function __construct()
 {
     global $conf;
     $this->cnf = $conf['auth']['ad'];
     // additional information fields
     if (isset($this->cnf['additional'])) {
         $this->cnf['additional'] = str_replace(' ', '', $this->cnf['additional']);
         $this->cnf['additional'] = explode(',', $this->cnf['additional']);
     } else {
         $this->cnf['additional'] = array();
     }
     // ldap extension is needed
     if (!function_exists('ldap_connect')) {
         if ($this->cnf['debug']) {
             msg("AD Auth: PHP LDAP extension not found.", -1);
         }
         $this->success = false;
         return;
     }
     // Prepare SSO
     if (!utf8_check($_SERVER['REMOTE_USER'])) {
         $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
     }
     if ($_SERVER['REMOTE_USER'] && $this->cnf['sso']) {
         // remove possible NTLM domain
         list($dom, $usr) = explode('\\', $_SERVER['REMOTE_USER'], 2);
         if (!$usr) {
             $usr = $dom;
         }
         // remove possible Kerberos domain
         list($usr, $dom) = explode('@', $usr);
         $dom = strtolower($dom);
         $_SERVER['REMOTE_USER'] = $usr;
         // we need to simulate a login
         if (empty($_COOKIE[DOKU_COOKIE])) {
             $_REQUEST['u'] = $_SERVER['REMOTE_USER'];
             $_REQUEST['p'] = 'sso_only';
         }
     }
     // prepare adLDAP standard configuration
     $this->opts = $this->cnf;
     // add possible domain specific configuration
     if ($dom && is_array($this->cnf[$dom])) {
         foreach ($this->cnf[$dom] as $key => $val) {
             $this->opts[$key] = $val;
         }
     }
     // handle multiple AD servers
     $this->opts['domain_controllers'] = explode(',', $this->opts['domain_controllers']);
     $this->opts['domain_controllers'] = array_map('trim', $this->opts['domain_controllers']);
     $this->opts['domain_controllers'] = array_filter($this->opts['domain_controllers']);
     // we can change the password if SSL is set
     if ($this->opts['use_ssl'] || $this->opts['use_tls']) {
         $this->cando['modPass'] = true;
     }
     $this->cando['modName'] = true;
     $this->cando['modMail'] = true;
 }
Ejemplo n.º 4
0
/**
 *  Output content of a file $filename in version of current language (otherwise may use an alternate language)
 *  @param      langs           Object language to use for output
 *  @param      filename        Relative filename to output
 *  @param      searchalt       1=Search also in alternative languages
 *	@return		boolean
 */
function dol_print_file($langs,$filename,$searchalt=0)
{
    global $conf;

    // Test if file is in lang directory
    foreach($langs->dir as $searchdir)
    {
        $htmlfile=($searchdir."/langs/".$langs->defaultlang."/".$filename);
        dol_syslog('functions2::dol_print_file search file '.$htmlfile, LOG_DEBUG);
        if (is_readable($htmlfile))
        {
            $content=file_get_contents($htmlfile);
            $isutf8=utf8_check($content);
            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
            elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
            else print $content;
            return true;
        }
        else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);

        if ($searchalt) {
            // Test si fichier dans repertoire de la langue alternative
            if ($langs->defaultlang != "en_US") $htmlfilealt = $searchdir."/langs/en_US/".$filename;
            else $htmlfilealt = $searchdir."/langs/fr_FR/".$filename;
            dol_syslog('functions2::dol_print_file search alt file '.$htmlfilealt, LOG_DEBUG);
            //print 'getcwd='.getcwd().' htmlfilealt='.$htmlfilealt.' X '.file_exists(getcwd().'/'.$htmlfilealt);
            if (is_readable($htmlfilealt))
            {
                $content=file_get_contents($htmlfilealt);
                $isutf8=utf8_check($content);
                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
                elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
                else print $content;
                return true;
            }
            else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
        }
    }

    return false;
}
Ejemplo n.º 5
0
 public function processTagUrl(array $tag, array $rendererStates)
 {
     if (!empty($tag['option'])) {
         $url = $tag['option'];
         $text = $this->renderSubTree($tag['children'], $rendererStates);
     } else {
         $url = $this->stringifyTree($tag['children']);
         $text = urldecode($url);
         if (!utf8_check($text)) {
             $text = $url;
         }
     }
     $validUrl = $this->_getValidUrl($url);
     if (!empty($validUrl)) {
         $this->_urls[$url] = $validUrl;
     }
     if (!empty($tag['option'])) {
         return "[URL={$this->_urlPrefix}{$url}{$this->_urlSuffix}]{$text}[/URL]";
     } else {
         return "[URL]{$this->_urlPrefix}{$url}{$this->_urlSuffix}[/URL]";
     }
 }
Ejemplo n.º 6
0
 /**
  * Sanitize a variable.
  * 
  * @param string $input
  * @param string $type
  * @return string|false
  */
 public static function sanitize($input, $type)
 {
     switch ($type) {
         // Escape HTML special characters.
         case 'escape':
             if (!utf8_check($input)) {
                 return false;
             }
             return escape($input);
             // Strip all HTML tags.
         // Strip all HTML tags.
         case 'strip':
             if (!utf8_check($input)) {
                 return false;
             }
             return escape(strip_tags($input));
             // Clean up HTML content to prevent XSS attacks.
         // Clean up HTML content to prevent XSS attacks.
         case 'html':
             if (!utf8_check($input)) {
                 return false;
             }
             return Filters\HTMLFilter::clean($input);
             // Clean up the input to be used as a safe filename.
         // Clean up the input to be used as a safe filename.
         case 'filename':
             if (!utf8_check($input)) {
                 return false;
             }
             return Filters\FilenameFilter::clean($input);
             // Unknown filters return false.
         // Unknown filters return false.
         default:
             return false;
     }
 }
Ejemplo n.º 7
0
/**
 * Function to put the movable box of a source field
 *
 * @param	array	$fieldssource	List of source fields
 * @param	int		$pos			Pos
 * @param	string	$key			Key
 * @param	boolean	$var			Line style (odd or not)
 * @param	int		$nostyle		Hide style
 * @return	void
 */
function show_elem($fieldssource, $pos, $key, $var, $nostyle = '')
{
    global $langs, $bc;
    print "\n\n<!-- Box " . $pos . " start -->\n";
    print '<div class="box" style="padding: 0px 0px 0px 0px;" id="boxto_' . $pos . '">' . "\n";
    print '<table summary="boxtable' . $pos . '" width="100%" class="nobordernopadding">' . "\n";
    if ($pos && $pos > count($fieldssource)) {
        print '<tr ' . ($nostyle ? '' : $bc[$var]) . ' height="20">';
        print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
        print img_picto($pos > 0 ? $langs->trans("MoveField", $pos) : '', 'uparrow', 'class="boxhandle" style="cursor:move;"');
        print '</td>';
        print '<td style="font-weight: normal">';
        print $langs->trans("NoFields");
        print '</td>';
        print '</tr>';
    } elseif ($key == 'none') {
        print '<tr ' . ($nostyle ? '' : $bc[$var]) . ' height="20">';
        print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
        print '&nbsp;';
        print '</td>';
        print '<td style="font-weight: normal">';
        print '&nbsp;';
        print '</td>';
        print '</tr>';
    } else {
        print '<tr ' . ($nostyle ? '' : $bc[$var]) . ' height="20">';
        print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
        // The image must have the class 'boxhandle' beause it's value used in DOM draggable objects to define the area used to catch the full object
        print img_picto($langs->trans("MoveField", $pos), 'uparrow', 'class="boxhandle" style="cursor:move;"');
        print '</td>';
        print '<td style="font-weight: normal">';
        print $langs->trans("Field") . ' ' . $pos;
        $example = $fieldssource[$pos]['example1'];
        if ($example) {
            if (!utf8_check($example)) {
                $example = utf8_encode($example);
            }
            print ' (<i>' . $example . '</i>)';
        }
        print '</td>';
        print '</tr>';
    }
    print "</table>\n";
    print "</div>\n";
    print "<!-- Box end -->\n\n";
}
Ejemplo n.º 8
0
 function is_photo_available($sdir)
 {
     include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     $pdir = get_exdir($this->id, 2) . $this->id . "/photos/";
     $dir = $sdir . '/' . $pdir;
     $nbphoto = 0;
     $dir_osencoded = dol_osencode($dir);
     if (file_exists($dir_osencoded)) {
         $handle = opendir($dir_osencoded);
         if (is_resource($handle)) {
             while (($file = readdir($handle)) != false) {
                 if (!utf8_check($file)) {
                     $file = utf8_encode($file);
                 }
                 // To be sure data is stored in UTF8 in memory
                 if (dol_is_file($dir . $file)) {
                     return true;
                 }
             }
         }
     }
     return false;
 }
Ejemplo n.º 9
0
/**
 *	Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
 *
 *	@param	string	$str			String to clean
 *	@return string   	       		Cleaned string
 *
 * 	@see    		dol_sanitizeFilename, dol_string_nospecial
 */
function dol_string_unaccent($str)
{
    if (utf8_check($str)) {
        // See http://www.utf8-chartable.de/
        $string = rawurlencode($str);
        $replacements = array('%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A', '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E', '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I', '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O', '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U', '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a', '%C3%A7' => 'c', '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e', '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i', '%C3%B1' => 'n', '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o', '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u', '%C3%BF' => 'y');
        $string = strtr($string, $replacements);
        return rawurldecode($string);
    } else {
        // See http://www.ascii-code.com/
        $string = strtr($str, "ÀÁÂÃÄÅÇ\n\t\t\tÈÉÊËÌÍÎÏÐÑ\n\t\t\tÒÓÔÕØÙÚÛÝ\n\t\t\tàáâãäåçèéêë\n\t\t\tìíîïðñòóôõø\n\t\t\tùúûüýÿ", "AAAAAAC\n\t\t\tEEEEIIIIDN\n\t\t\tOOOOOUUUY\n\t\t\taaaaaaceeee\n\t\t\tiiiidnooooo\n\t\t\tuuuuyy");
        $string = strtr($string, array("Ä" => "Ae", "Æ" => "AE", "Ö" => "Oe", "Ü" => "Ue", "Þ" => "TH", "ß" => "ss", "ä" => "ae", "æ" => "ae", "ö" => "oe", "ü" => "ue", "þ" => "th"));
        return $string;
    }
}
Ejemplo n.º 10
0
 /**
  * Returns one random cookie
  *
  * @author Andreas Gohr <*****@*****.**>
  */
 function _getCookie($cookie)
 {
     $file = mediaFN($cookie);
     if (!@file_exists($file)) {
         return 'ERROR: cookie file not found';
     }
     $dim = filesize($file);
     if ($dim < 2) {
         return "ERROR: invalid cookie file {$file}";
     }
     mt_srand((double) microtime() * 1000000);
     $rnd = mt_rand(0, $dim);
     $fd = fopen($file, 'r');
     if (!$fd) {
         return "ERROR: reading cookie file {$file} failed";
     }
     // jump to random place in file
     fseek($fd, $rnd);
     $text = '';
     $line = '';
     $cookie = false;
     $test = 0;
     while (true) {
         $seek = ftell($fd);
         $line = fgets($fd, 1024);
         if ($seek == 0) {
             // start of file always starts a cookie
             $cookie = true;
             if ($line == "%\n") {
                 // ignore delimiter if exists
                 continue;
             } else {
                 // part of the cookie
                 $text .= htmlspecialchars($line) . '<br />';
                 continue;
             }
         }
         if (feof($fd)) {
             if ($cookie) {
                 // we had a cookie already, stop here
                 break;
             } else {
                 // no cookie yet, wrap around
                 fseek($fd, 0);
                 continue;
             }
         }
         if ($line == "%\n") {
             if ($cookie) {
                 // we had a cookie already, stop here
                 break;
             } elseif ($seek == $dim - 2) {
                 // it's the end of file delimiter, wrap around
                 fseek($fd, 0);
                 continue;
             } else {
                 // start of the cookie
                 $cookie = true;
                 continue;
             }
         }
         // part of the cookie?
         if ($cookie) {
             $text .= htmlspecialchars($line) . '<br />';
         }
     }
     fclose($fd);
     // if it is not valid UTF-8 assume it's latin1
     if (!utf8_check($text)) {
         return utf8_encode($text);
     }
     return $text;
 }
Ejemplo n.º 11
0
 /**
  * 进行转换
  *
  * 说明:
  *   - iconv 下会忽略在目标字符集中不存在的字符
  *   - 查表方法使用 UTF-16BE 作为中间编码进行转换
  *   - 非 mbstring 方式由 HTML-ENTITIES(NCR) 转换到非 UTF-8 编码使用 UTF-8 作中间编码
  *   - 转换到 pinyin 使用 GBK 作中间编码
  *
  *
  * @param string $str 要转换的字符串
  * @param string $from 不填写将直接使用属性 from_encoding
  * @param string $to 不填写将直接使用属性 to_encoding
  * @return string 转换后的字符串
  */
 function convert($str, $from = '', $to = '')
 {
     if ($this->set($from, $to) && !empty($str) && $this->from_encoding != $this->to_encoding) {
         if (in_array($this->from_encoding, array('traditional', 'simplified')) || in_array($this->to_encoding, array('traditional', 'simplified'))) {
             if (utf8_check($str)) {
                 if ($this->from_encoding == 'simplified' && $this->to_encoding == 'traditional') {
                     return utf8_traditional_zh($str);
                 } else {
                     if ($this->from_encoding == 'traditional' && $this->to_encoding == 'simplified') {
                         return utf8_simplified_zh($str);
                     }
                 }
             }
             return $str;
         }
         if ($this->to_encoding == 'pinyin') {
             if ($this->from_encoding != 'gbk') {
                 $from_encoding = $this->from_encoding;
                 $str = $this->convert($str, $this->from_encoding, 'gbk');
                 $this->from_encoding = $from_encoding;
                 $this->to_encoding = 'pinyin';
             }
             return $this->gbk2pin($str);
         }
         switch ($this->type) {
             case 'mbstring':
                 return mb_convert_encoding($str, $this->to_encoding, $this->from_encoding);
             case 'iconv':
                 if ($this->to_encoding == 'html-entities') {
                     $str = iconv($this->from_encoding, 'utf-16be', $str);
                     return $this->unicode2htm($str);
                 } else {
                     if ($this->from_encoding != 'html-entities') {
                         return iconv($this->from_encoding, $this->to_encoding . '//IGNORE', $str);
                     }
                 }
             default:
                 if ($this->from_encoding == 'utf-8' && $this->to_encoding == 'html-entities') {
                     return utf8_to_ncr($str);
                 } else {
                     if ($this->from_encoding == 'html-entities') {
                         $str = utf8_from_ncr($str);
                         if ($this->to_encoding != 'utf-8') {
                             $str = $this->convert($str, 'utf-8', $this->to_encoding);
                             $this->from_encoding = 'html-entities';
                         }
                         return $str;
                     } else {
                         $space = array("\n", "\r", "\t");
                         $tag = array('<|n|>', '<|r|>', '<|t|>');
                         $str = str_replace($space, $tag, $str);
                         $method_name = substr($this->from_encoding, 0, 3);
                         $to_unicode = $method_name . '2unicode';
                         if ($this->from_encoding == 'utf-16le') {
                             $str = $this->change_byte($str);
                         } else {
                             if ($this->from_encoding != 'utf-16be' && method_exists($this, $to_unicode)) {
                                 $str = $this->{$to_unicode}($str);
                             }
                         }
                         $from_unicode = 'unicode2' . $method_name;
                         if ($this->to_encoding == 'utf-16le') {
                             $str = $this->change_byte($str);
                         } else {
                             if ($this->to_encoding != 'utf-16be' && method_exists($this, $from_unicode)) {
                                 $str = $this->{$from_unicode}($str);
                             }
                         }
                         return str_replace($tag, $space, $str);
                     }
                 }
         }
     } else {
         return $str;
     }
 }
Ejemplo n.º 12
0
/**
 * convert line ending to unix format
 *
 * also makes sure the given text is valid UTF-8
 *
 * @see    formText() for 2crlf conversion
 * @author Andreas Gohr <*****@*****.**>
 *
 * @param string $text
 * @return string
 */
function cleanText($text)
{
    $text = preg_replace("/(\r\n)|(\r)/", "\n", $text);
    // if the text is not valid UTF-8 we simply assume latin1
    // this won't break any worse than it breaks with the wrong encoding
    // but might actually fix the problem in many cases
    if (!utf8_check($text)) {
        $text = utf8_encode($text);
    }
    return $text;
}
Ejemplo n.º 13
0
/**
 * Remove BOM and invalid UTF-8 sequences from file content.
 * 
 * @param string $str
 * @return string
 */
function utf8_clean($str)
{
    if (strlen($str) >= 3 && substr($str, 0, 3) === "") {
        $str = substr($str, 3);
    }
    if (!utf8_check($str)) {
        $str = @iconv('UTF-8', 'UTF-8//IGNORE', $str);
    }
    return $str;
}
 /**
  * Try to create a socket connection
  *
  * @param 	string		$host		Add ssl:// for SSL/TLS.
  * @param 	int			$port		Example: 25, 465
  * @return	int						Socket id if ok, 0 if KO
  */
 function check_server_port($host, $port)
 {
     $_retVal = 0;
     $timeout = 5;
     // Timeout in seconds
     if (function_exists('fsockopen')) {
         dol_syslog("Try socket connection to host=" . $host . " port=" . $port);
         //See if we can connect to the SMTP server
         if ($socket = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
             // Windows still does not have support for this timeout function
             if (function_exists('stream_set_timeout')) {
                 stream_set_timeout($socket, $timeout, 0);
             }
             dol_syslog("Now we wait for answer 220");
             // Check response from Server
             if ($_retVal = $this->server_parse($socket, "220")) {
                 $_retVal = $socket;
             }
         } else {
             $this->error = utf8_check('Error ' . $errno . ' - ' . $errstr) ? 'Error ' . $errno . ' - ' . $errstr : utf8_encode('Error ' . $errno . ' - ' . $errstr);
         }
     }
     return $_retVal;
 }
Ejemplo n.º 15
0
/**
 * Highlights searchqueries in HTML code
 *
 * @author Andreas Gohr <*****@*****.**>
 * @author Harry Fuecks <*****@*****.**>
 */
function html_hilight($html, $phrases)
{
    $phrases = array_filter((array) $phrases);
    $regex = join('|', array_map('ft_snippet_re_preprocess', array_map('preg_quote_cb', $phrases)));
    if ($regex === '') {
        return $html;
    }
    if (!utf8_check($regex)) {
        return $html;
    }
    $html = @preg_replace_callback("/((<[^>]*)|{$regex})/ui", 'html_hilight_callback', $html);
    return $html;
}
Ejemplo n.º 16
0
 /**
  * Convert strings into UTF-8
  *
  * @param string $str String to convert
  * @return string converted string
  */
 public static function convertEncodingStr($str)
 {
     if (!$str || utf8_check($str)) {
         return $str;
     }
     $obj = new stdClass();
     $obj->str = $str;
     $obj = self::convertEncoding($obj);
     return $obj->str;
 }
Ejemplo n.º 17
0
/**
 *  Remove a directory $dir and its subdirectories (or only files and subdirectories)
 *
 *  @param	string	$dir            Dir to delete
 *  @param  int		$count          Counter to count nb of deleted elements
 *  @param  int		$nophperrors    Disable all PHP output errors
 *  @param	int		$onlysub		Delete only files and subdir, not main directory
 *  @return int             		Number of files and directory removed
 */
function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0)
{
    dol_syslog("functions.lib:dol_delete_dir_recursive " . $dir, LOG_DEBUG);
    if (dol_is_dir($dir)) {
        $dir_osencoded = dol_osencode($dir);
        if ($handle = opendir("{$dir_osencoded}")) {
            while (false !== ($item = readdir($handle))) {
                if (!utf8_check($item)) {
                    $item = utf8_encode($item);
                }
                // should be useless
                if ($item != "." && $item != "..") {
                    if (is_dir(dol_osencode("{$dir}/{$item}"))) {
                        $count = dol_delete_dir_recursive("{$dir}/{$item}", $count, $nophperrors);
                    } else {
                        dol_delete_file("{$dir}/{$item}", 1, $nophperrors);
                        $count++;
                        //echo " removing $dir/$item<br>\n";
                    }
                }
            }
            closedir($handle);
            if (empty($onlysub)) {
                dol_delete_dir($dir, $nophperrors);
                $count++;
                //echo "removing $dir<br>\n";
            }
        }
    }
    //echo "return=".$count;
    return $count;
}
Ejemplo n.º 18
0
 /**
  * Create output
  */
 function render($mode, Doku_Renderer &$renderer, $opt)
 {
     if ($mode == 'metadata') {
         return false;
     }
     // load file data
     if ($opt['file']) {
         if (preg_match('/^https?:\\/\\//i', $opt['file'])) {
             require_once DOKU_INC . 'inc/HTTPClient.php';
             $http = new DokuHTTPClient();
             $opt['content'] = $http->get($opt['file']);
             if ($opt['content'] === false) {
                 $renderer->cdata('Failed to fetch remote CSV data');
                 return true;
             }
         } else {
             $renderer->info['cache'] = false;
             if (auth_quickaclcheck(getNS($opt['file']) . ':*') < AUTH_READ) {
                 $renderer->cdata('Access denied to CSV data');
                 return true;
             } else {
                 $file = mediaFN($opt['file']);
                 $opt['content'] = io_readFile($file);
             }
         }
         // if not valid UTF-8 is given we assume ISO-8859-1
         if (!utf8_check($opt['content'])) {
             $opt['content'] = utf8_encode($opt['content']);
         }
     }
     // check if there is content
     $content =& $opt['content'];
     $content = trim($content);
     if ($content === '') {
         $renderer->cdata('No csv data found');
         return true;
     }
     // Export the csv file
     $targetfile = '';
     $export = $opt['export'];
     if ($export != '') {
         $targetfile = htmlspecialchars(trim($export));
         if (auth_quickaclcheck(getNS($targetfile . ':*')) < AUTH_EDIT) {
             $renderer->cdata('Access denied: Could not create download link.');
             $targetfile = '';
             return true;
         } else {
             $file = mediaFN($targetfile);
             if (file_put_contents($file, $content, LOCK_EX) > 0) {
                 $linkname = $opt['linkname'];
                 if ($linkname == '') {
                     $linkname = 'Download CSV file';
                 }
             } else {
                 $targetfile = '';
                 $renderer->cdata('Failed to write ' . $file . ': Could not create download link.');
                 return true;
             }
         }
     }
     // get the first row - it will define the structure
     $row = $this->csv_explode_row($content, $opt['delim'], $opt['enclosure'], $opt['escape']);
     $maxcol = count($row);
     $line = 0;
     // create the table and start rendering
     $renderer->table_open($maxcol);
     while ($row !== false) {
         // make sure we have enough columns
         $row = array_pad($row, $maxcol, '');
         // render
         $renderer->tablerow_open();
         for ($i = 0; $i < $maxcol;) {
             $span = 1;
             // lookahead to find spanning cells
             if ($opt['span_empty_cols']) {
                 for ($j = $i + 1; $j < $maxcol; $j++) {
                     if ($row[$j] === '') {
                         $span++;
                     } else {
                         break;
                     }
                 }
             }
             // open cell
             if ($line < $opt['hdr_rows'] || $i < $opt['hdr_cols']) {
                 $renderer->tableheader_open($span);
             } else {
                 $renderer->tablecell_open($span);
             }
             // print cell content, call linebreak() for newlines
             $lines = explode("\n", $row[$i]);
             $cnt = count($lines);
             for ($k = 0; $k < $cnt; $k++) {
                 $renderer->cdata($lines[$k]);
                 if ($k < $cnt - 1) {
                     $renderer->linebreak();
                 }
             }
             // close cell
             if ($line < $opt['hdr_rows'] || $i < $opt['hdr_cols']) {
                 $renderer->tableheader_close();
             } else {
                 $renderer->tablecell_close();
             }
             $i += $span;
         }
         $renderer->tablerow_close();
         // get next row
         $row = $this->csv_explode_row($content, $opt['delim'], $opt['enclosure'], $opt['escape']);
         $line++;
     }
     $renderer->table_close();
     if ($targetfile != '') {
         $renderer->internalmedia($targetfile, $linkname);
     }
     return true;
 }
Ejemplo n.º 19
0
    /**
     *  Charge les donnees en memoire pour affichage ulterieur
     *  @param      $max        Nombre maximum d'enregistrements a charger
     */
    function loadBox($max=5)
    {
        global $user, $langs, $conf;
        $langs->load("boxes");

		$this->max=$max;

		// On recupere numero de param de la boite
		preg_match('/^([0-9]+) /',$this->param,$reg);
		$site=$reg[1];

		// Creation rep (pas besoin, on le cree apres recup flux)
		// documents/rss is created by module activation
		// documents/rss/tmp is created by magpie
		//$result=create_exdir($conf->externalrss->dir_temp);

		// Recupere flux RSS definie dans EXTERNAL_RSS_URLRSS_$site
        $url=@constant("EXTERNAL_RSS_URLRSS_".$site);
        //define('MAGPIE_DEBUG',1);
        $rss=fetch_rss($url);
        if (! is_object($rss))
        {
        	dol_syslog("FETCH_RSS site=".$site);
        	dol_syslog("FETCH_RSS url=".$url);
        	return -1;
        }

		// INFO sur le channel
		$description=$rss->channel['tagline'];
		$link=$rss->channel['link'];

        $title=$langs->trans("BoxTitleLastRssInfos",$max, @constant("EXTERNAL_RSS_TITLE_". $site));
        if ($rss->ERROR)
        {
            // Affiche warning car il y a eu une erreur
            $title.=" ".img_error($langs->trans("FailedToRefreshDataInfoNotUpToDate",(isset($rss->date)?dol_print_date($rss->date,"dayhourtext"):$langs->trans("Unknown"))));
            $this->info_box_head = array('text' => $title,'limit' => 0);
        }
        else
        {
        	$this->info_box_head = array('text' => $title,
        		'sublink' => $link, 'subtext'=>$langs->trans("LastRefreshDate").': '.(isset($rss->date)?dol_print_date($rss->date,"dayhourtext"):$langs->trans("Unknown")), 'subpicto'=>'object_bookmark');
		}

		// INFO sur le elements
        for($i = 0; $i < $max && $i < sizeof($rss->items); $i++)
        {
            $item = $rss->items[$i];

			// Magpierss common fields
            $href  = $item['link'];
        	$title = urldecode($item['title']);
			$date  = $item['date_timestamp'];	// date will be empty if conversion into timestamp failed
			if ($rss->is_rss())		// If RSS
			{
				if (! $date && isset($item['pubdate']))    $date=$item['pubdate'];
				if (! $date && isset($item['dc']['date'])) $date=$item['dc']['date'];
				//$item['dc']['language']
				//$item['dc']['publisher']
			}
			if ($rss->is_atom())	// If Atom
			{
				if (! $date && isset($item['issued']))    $date=$item['issued'];
				if (! $date && isset($item['modified']))  $date=$item['modified'];
				//$item['issued']
				//$item['modified']
				//$item['atom_content']
			}
			if (is_numeric($date)) $date=dol_print_date($date,"dayhour");

			$isutf8 = utf8_check($title);
	        if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') $title=utf8_encode($title);
	        elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') $title=utf8_decode($title);

	        $title=preg_replace("/([[:alnum:]])\?([[:alnum:]])/","\\1'\\2",$title);   // Gere probleme des apostrophes mal codee/decodee par utf8
            $title=preg_replace("/^\s+/","",$title);                                  // Supprime espaces de debut
            $this->info_box_contents["$href"]="$title";

            $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"',
            'logo' => $this->boximg,
            'url' => $href,
            'target' => 'newrss');

            $this->info_box_contents[$i][1] = array('td' => 'align="left"',
            'text' => $title,
            'url' => $href,
            'maxlength' => 64,
            'target' => 'newrss');

            $this->info_box_contents[$i][2] = array('td' => 'align="right" nowrap="1"',
            'text' => $date);
        }
    }
Ejemplo n.º 20
0
    /**
     * testDolTextIsHtml
     *
     * @return void
     */
    public function testDolUtf8Check()
    {
        // True
        $result=utf8_check('azerty');
        $this->assertTrue($result);

        $file=dirname(__FILE__).'/textutf8.txt';
        $filecontent=file_get_contents($file);
        $result=utf8_check($filecontent);
        $this->assertTrue($result);

        $file=dirname(__FILE__).'/textiso.txt';
        $filecontent=file_get_contents($file);
        $result=utf8_check($filecontent);
        $this->assertFalse($result);
    }
Ejemplo n.º 21
0
 /**
  * Import a file of users in csv format
  *
  * csv file should have 4 columns, user_id, full name, email, groups (comma separated)
  *
  * @return bool whether successful
  */
 protected function _import()
 {
     // check we are allowed to add users
     if (!checkSecurityToken()) {
         return false;
     }
     if (!$this->_auth->canDo('addUser')) {
         return false;
     }
     // check file uploaded ok.
     if (empty($_FILES['import']['size']) || !empty($_FILES['import']['error']) && $this->_isUploadedFile($_FILES['import']['tmp_name'])) {
         msg($this->lang['import_error_upload'], -1);
         return false;
     }
     // retrieve users from the file
     $this->_import_failures = array();
     $import_success_count = 0;
     $import_fail_count = 0;
     $line = 0;
     $fd = fopen($_FILES['import']['tmp_name'], 'r');
     if ($fd) {
         while ($csv = fgets($fd)) {
             if (!utf8_check($csv)) {
                 $csv = utf8_encode($csv);
             }
             $raw = $this->_getcsv($csv);
             $error = '';
             // clean out any errors from the previous line
             // data checks...
             if (1 == ++$line) {
                 if ($raw[0] == 'user_id' || $raw[0] == $this->lang['user_id']) {
                     continue;
                 }
                 // skip headers
             }
             if (count($raw) < 4) {
                 // need at least four fields
                 $import_fail_count++;
                 $error = sprintf($this->lang['import_error_fields'], count($raw));
                 $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
                 continue;
             }
             array_splice($raw, 1, 0, auth_pwgen());
             // splice in a generated password
             $clean = $this->_cleanImportUser($raw, $error);
             if ($clean && $this->_addImportUser($clean, $error)) {
                 $sent = $this->_notifyUser($clean[0], $clean[1], false);
                 if (!$sent) {
                     msg(sprintf($this->lang['import_notify_fail'], $clean[0], $clean[3]), -1);
                 }
                 $import_success_count++;
             } else {
                 $import_fail_count++;
                 array_splice($raw, 1, 1);
                 // remove the spliced in password
                 $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
             }
         }
         msg(sprintf($this->lang['import_success_count'], $import_success_count + $import_fail_count, $import_success_count), $import_success_count ? 1 : -1);
         if ($import_fail_count) {
             msg(sprintf($this->lang['import_failure_count'], $import_fail_count), -1);
         }
     } else {
         msg($this->lang['import_error_readfail'], -1);
     }
     // save import failures into the session
     if (!headers_sent()) {
         session_start();
         $_SESSION['import_failures'] = $this->_import_failures;
         session_write_close();
     }
     return true;
 }
 function validate_import($object)
 {
     global $langs, $conf;
     $this->process_msg = '';
     $error = 0;
     if (!utf8_check($this->filename)) {
         ${$this}->filename = utf8_encode($this->filename);
     }
     $fp = @fopen($this->filename, "r");
     if ($fp) {
         switch ($object) {
             case 'ImportStock':
                 $doliprod = new Product($this->db);
                 $i = 0;
                 while ($ligne = fgetcsv($fp, 1000, ";")) {
                     $doliprod->id = '';
                     $i++;
                     if ($this->firstline && $i == 1) {
                         continue;
                     }
                     if ($conf->global->IMPORT_BARCODE) {
                         $ligne[0] = $this->get_product_by_barcode($ligne[0]);
                     }
                     if ($doliprod->fetch('', $ligne[0]) <= 0) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrProdNoExist", $ligne[0], $doliprod->error) . "\n";
                         $error--;
                     }
                     $this->process_msg .= "\n";
                 }
                 break;
             case 'ImportProduct':
                 $doliprod = new Product($this->db);
                 $i = 0;
                 while ($ligne = fgetcsv($fp, 1000, ";")) {
                     $doliprod->id = '';
                     $i++;
                     if ($this->firstline && $i == 1) {
                         continue;
                     }
                     if (!$ligne[0]) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrRefRequired") . "\n";
                         $error--;
                     }
                     $this->process_msg .= "\n";
                 }
                 break;
             case 'Importtarif':
                 $doliprod = new Product($this->db);
                 $societe = new Societe($this->db);
                 $i = 0;
                 while ($ligne = fgetcsv($fp, 1000, ";")) {
                     $doliprod->id = '';
                     $i++;
                     if ($this->firstline && $i == 1) {
                         continue;
                     }
                     if ($doliprod->fetch('', $ligne[0]) <= 0) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrProdNoExist", $ligne[0], $doliprod->error) . "\n";
                         $error--;
                     }
                     if (!$ligne[1]) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrRefRequired") . "\n";
                         $error--;
                     }
                     if ($societe->fetch('', $ligne[2]) < 0) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrCompanyNoExist", $ligne[2], $societe->error) . "\n";
                         $error--;
                     }
                     $this->process_msg .= "\n";
                 }
                 break;
             case 'ImportThirtdparty':
                 $i = 0;
                 while ($ligne = fgetcsv($fp, 1000, ";")) {
                     $i++;
                     if ($this->firstline && $i == 1) {
                         continue;
                     }
                     if (!$ligne[0]) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrNameRequired", $ligne[0]) . "\n";
                         $error--;
                     }
                 }
                 break;
             case 'ImportContact':
                 $i = 0;
                 $societe = new Societe($this->db);
                 while ($ligne = fgetcsv($fp, 1000, ";")) {
                     $i++;
                     if ($this->firstline && $i == 1) {
                         continue;
                     }
                     // recherche id Société
                     if ($ligne[0]) {
                         $socid = $this->get_socbyclientcode($ligne[0]);
                     } else {
                         if ($ligne[1]) {
                             $socid = $this->get_socbysuplliercode($ligne[1]);
                         }
                     }
                     if ($socid <= 0) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrCompanyRequired") . "\n";
                         $error--;
                     } else {
                         $societe->fetch($socid);
                         if (!$societe->id) {
                             $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrCompanyNoExist", $ligne[0] . " " . $ligne[1]) . "\n";
                             $error--;
                         }
                     }
                     // test existence contact
                     if (empty($ligne[2])) {
                         $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrNameRequired") . "\n";
                     }
                 }
                 break;
                 /*case 'ImportActions':
                 		$i=0;
                 		$contact=new Contact($this->db);
                 		$societe = new Societe($this->db);
                 		$actioncomm = new ActionComm($this->db);
                 		$actuser = new User($this->db);
                 		
                 		while ($ligne = fgetcsv($fp,1000,";"))
                 		{
                 			$i++;
                 			if ($this->firstline && $i== 1) continue;
                 			
                 			if ($societe->fetch('',$ligne[0]) < 0 ){ 
                 				$this->process_msg .= $langs->trans("Untreated",$i)." ".$langs->trans("ErrCompanyNoExist",$ligne[0])."\n";
                 				$error--;				
                 			}
                 			else $socid = $societe->id;
                 			
                 			if (!$socid) 
                 			{
                 				$this->process_msg .= $langs->trans("Untreated",$i)." ".$langs->trans("ErrCompanyNoExist",$ligne[0])."\n";
                 				$error--;
                 			}
                 			$usertodo = '';
                 			if ($ligne[9])
                 			{
                 				if ($actuser->fetch('',$ligne[9]) < 0) {
                 					$this->process_msg .= $langs->trans("Untreated",$i)." ".$langs->trans("ErrUserNoExist",$ligne[9])."\n";
                 					$error--;
                 				}
                 				else $usertodo = $actuser->id;
                 			}
                 			$userdone= '' ;
                 			if ($ligne[10])
                 			{
                 				if ($actuser->fetch('',$ligne[10]) < 0) {
                 					$this->process_msg .= $langs->trans("Untreated",$i)." ".$langs->trans("ErrUserNoExist",$ligne[10])."\n";
                 				}
                 				else $userdone = $actuser->id;
                 			}
                 			if ($ligne[6])
                 			{
                 				// voir date
                 				$n = sscanf($ligne[6],"%02d/%02d/%04d", $d_day, $d_mon, $d_year);
                 				if ($n==3) $datep=dol_mktime(12, 0, 0, $d_mon, $d_day, $d_year);
                 				else {
                 					$this->process_msg .= $langs->trans("Untreated",$i)." ".$langs->trans("ErrDateConversion",$ligne[6])."\n";
                 					$error--;
                 				}
                 			}
                 			if ($ligne[7])
                 			{
                 				// voir date
                 				$n = sscanf($ligne[7],"%02d/%02d/%04d", $d_day, $d_mon, $d_year);
                 				if ($n==3) $datep=dol_mktime(12, 0, 0, $d_mon, $d_day, $d_year);
                 				else {
                 					$this->process_msg .= $langs->trans("Untreated",$i)." ".$langs->trans("ErrDateConversion",$ligne[7])."\n";
                 				}
                 			}
                 			
                 			$langs->trans("Treaty",$i)."\n";
                 		}
                 		break;	*/
         }
         fclose($fp);
     } else {
         $this->error = $lang->trans("ErrorOpenFile", $nomfich);
         $error = -1;
     }
     return $error;
 }
Ejemplo n.º 23
0
 /**
  *  Retourne tableau de toutes les photos du produit
  *
  *  @param      string		$dir        Repertoire a scanner
  *  @param      int			$nbmax      Nombre maximum de photos (0=pas de max)
  *  @return     array       			Tableau de photos
  */
 function liste_photos($dir, $nbmax = 0)
 {
     include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     $nbphoto = 0;
     $tabobj = array();
     $dir_osencoded = dol_osencode($dir);
     $handle = @opendir($dir_osencoded);
     if (is_resource($handle)) {
         while (($file = readdir($handle)) != false) {
             if (!utf8_check($file)) {
                 $file = utf8_encode($file);
             }
             // readdir returns ISO
             if (dol_is_file($dir . $file) && preg_match('/(' . $this->regeximgext . ')$/i', $dir . $file)) {
                 $nbphoto++;
                 // On determine nom du fichier vignette
                 $photo = $file;
                 $photo_vignette = '';
                 if (preg_match('/(' . $this->regeximgext . ')$/i', $photo, $regs)) {
                     $photo_vignette = preg_replace('/' . $regs[0] . '/i', '', $photo) . '_small' . $regs[0];
                 }
                 $dirthumb = $dir . 'thumbs/';
                 // Objet
                 $obj = array();
                 $obj['photo'] = $photo;
                 if ($photo_vignette && dol_is_file($dirthumb . $photo_vignette)) {
                     $obj['photo_vignette'] = 'thumbs/' . $photo_vignette;
                 } else {
                     $obj['photo_vignette'] = "";
                 }
                 $tabobj[$nbphoto - 1] = $obj;
                 // On continue ou on arrete de boucler ?
                 if ($nbmax && $nbphoto >= $nbmax) {
                     break;
                 }
             }
         }
         closedir($handle);
     }
     return $tabobj;
 }
Ejemplo n.º 24
0
/**
 *	Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
 *	@param          str             String to clean
 *	@return         string          Cleaned string
 * 	@see    		dol_sanitizeFilename, dol_string_nospecial
 */
function dol_string_unaccent($str)
{
    if (utf8_check($str)) {
        $string = rawurlencode($str);
        $replacements = array('%C3%80' => 'A', '%C3%81' => 'A', '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%92' => 'O', '%C3%93' => 'O', '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e', '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B9' => 'u', '%C3%BA' => 'u');
        $string = strtr($string, $replacements);
        return rawurldecode($string);
    } else {
        $string = strtr($str, "ÀÁÂÃÅÇ\n\t        ÈÉÊËÌÍÎÏÐÑ\n\t        ÒÓÔÕØÙÚÛÝ\n\t        àáâãåçèéêë\n\t        ìíîïðñòóôõø\n\t        ùúûýÿ", "AAAAAC\n\t        EEEEIIIIDN\n\t        OOOOOUUUY\n\t        aaaaaceeee\n\t        iiiidnooooo\n\t        uuuyy");
        $string = strtr($string, array("Ä" => "Ae", "Æ" => "AE", "Ö" => "Oe", "Ü" => "Ue", "Þ" => "TH", "ß" => "ss", "ä" => "ae", "æ" => "ae", "ö" => "oe", "ü" => "ue", "þ" => "th"));
        return $string;
    }
}
Ejemplo n.º 25
0
 /**
  * 	Return array of next record in input file.
  *
  * 	@return		Array		Array of field values. Data are UTF8 encoded. [fieldpos] => (['val']=>val, ['type']=>-1=null,0=blank,1=not empty string)
  */
 function import_read_record()
 {
     global $conf;
     $arrayres = fgetcsv($this->handle, 100000, $this->separator, $this->enclosure, $this->escape);
     // End of file
     if ($arrayres === false) {
         return false;
     }
     //var_dump($this->handle);
     //var_dump($arrayres);exit;
     $newarrayres = array();
     if ($arrayres && is_array($arrayres)) {
         foreach ($arrayres as $key => $val) {
             if (!empty($conf->global->IMPORT_CSV_FORCE_CHARSET)) {
                 if (strtolower($conf->global->IMPORT_CSV_FORCE_CHARSET) == 'utf8') {
                     $newarrayres[$key]['val'] = $val;
                     $newarrayres[$key]['type'] = dol_strlen($val) ? 1 : -1;
                     // If empty we considere it's null
                 } else {
                     $newarrayres[$key]['val'] = utf8_encode($val);
                     $newarrayres[$key]['type'] = dol_strlen($val) ? 1 : -1;
                     // If empty we considere it's null
                 }
             } else {
                 if (utf8_check($val)) {
                     $newarrayres[$key]['val'] = $val;
                     $newarrayres[$key]['type'] = dol_strlen($val) ? 1 : -1;
                     // If empty we considere it's null
                 } else {
                     $newarrayres[$key]['val'] = utf8_encode($val);
                     $newarrayres[$key]['type'] = dol_strlen($val) ? 1 : -1;
                     // If empty we considere it's null
                 }
             }
         }
         $this->col = count($newarrayres);
     }
     return $newarrayres;
 }
Ejemplo n.º 26
0
 function render($mode, &$renderer, $opt)
 {
     if ($mode == 'metadata') {
         return false;
     }
     // load file data
     if ($opt['file']) {
         if (preg_match('/^https?:\\/\\//i', $opt['file'])) {
             require_once DOKU_INC . 'inc/HTTPClient.php';
             $http = new DokuHTTPClient();
             $opt['content'] = $http->get($opt['file']);
             if (!$opt['content']) {
                 $renderer->cdata('Failed to fetch remote CSV data');
                 return true;
             }
         } else {
             $renderer->info['cache'] = false;
             //no caching
             if (auth_quickaclcheck(getNS($opt['file']) . ':*') < AUTH_READ) {
                 $renderer->cdata('Access denied to CSV data');
                 return true;
             } else {
                 $file = mediaFN($opt['file']);
                 $opt['content'] = io_readFile($file);
                 // if not valid UTF-8 is given we assume ISO-8859-1
                 if (!utf8_check($opt['content'])) {
                     $opt['content'] = utf8_encode($opt['content']);
                 }
             }
         }
     }
     $content =& $opt['content'];
     // clear any trailing or leading empty lines from the data set
     $content = preg_replace("/[\r\n]*\$/", "", $content);
     $content = preg_replace("/^\\s*[\r\n]*/", "", $content);
     if (!trim($content)) {
         $renderer->cdata('No csv data found');
     }
     $rows = array();
     $maxcol = 0;
     $maxrow = 0;
     while ($content != "") {
         $thisrow = $this->csv_explode_row($content, $opt['delim']);
         if ($maxcol < count($thisrow)) {
             $maxcol = count($thisrow);
         }
         array_push($rows, $thisrow);
         //$cells = $this->csv_explode_row($content,$opt['delim']);
         // some spreadsheet systems (i.e., excell) appear to
         // denote column spans with a completely empty cell
         // (to adjacent commas) and an 'empty' cell will
         // contain at least one blank space, so if the user
         // asks, use that for attempting to span columns
         // together
         $maxrow++;
     }
     // render table we need values e.g. for ODT plugin ... -jerry
     $renderer->table_open($maxcol, $maxrow);
     $row = 1;
     foreach ($rows as $cells) {
         $renderer->tablerow_open();
         $spans = array();
         $span = 0;
         $current = 0;
         foreach ($cells as $cell) {
             if ($cell == '' && $opt['span_empty_cols']) {
                 $spans[$current] = 0;
                 $spans[$span]++;
             } else {
                 $spans[$current] = 1;
                 $span = $current;
             }
             $current++;
         }
         //handle empty line feature ;-) jerry
         if ($current < 2) {
             $spans[0] = $maxcol;
         }
         $current = 0;
         foreach ($cells as $cell) {
             $cell = preg_replace('/\\\\\\\\/', ' ', $cell);
             if ($spans[$current] > 0) {
                 $align = 'left';
                 if ($spans[$current] > 1) {
                     $align = 'center';
                 }
                 if ($row <= $opt['hdr_rows'] || $current < $opt['hdr_cols'] || $current == 0 && $spans[0] == $maxcol) {
                     $renderer->tableheader_open($spans[$current], $align);
                 } else {
                     $renderer->tablecell_open($spans[$current], $align);
                 }
                 $renderer->cdata($cell);
                 if ($row <= $opt['hdr_rows'] || $current < $opt['hdr_cols'] || $current == 0 && $spans[0] == $maxcol) {
                     $renderer->tableheader_close();
                 } else {
                     $renderer->tablecell_close();
                 }
             }
             $current++;
         }
         $renderer->tablerow_close();
         $row++;
     }
     $renderer->table_close();
     return true;
 }
Ejemplo n.º 27
0
	/**
	 * 	\brief		Return array of next record in input file.
	 * 	\return		Array		Array of field values. Data are UTF8 encoded.
	 * 							[0] => (['val']=>val, ['type']=>-1=null,0=blank,1=string)
	 */
	function import_read_record()
	{
		global $conf;

		$arrayres=array();
		if (version_compare(phpversion(), '5.3') < 0)
		{
			$arrayres=fgetcsv($this->handle,100000,$this->separator,$this->enclosure);
		}
		else
		{
			$arrayres=fgetcsv($this->handle,100000,$this->separator,$this->enclosure,$this->escape);
		}

		//var_dump($this->handle);
		//var_dump($arrayres);exit;
		$newarrayres=array();
		if ($arrayres && is_array($arrayres))
		{
			foreach($arrayres as $key => $val)
			{
				if (! empty($conf->global->IMPORT_CSV_FORCE_CHARSET))	// Forced charset
				{
					if (strtolower($conf->global->IMPORT_CSV_FORCE_CHARSET) == 'utf8')
					{
						$newarrayres[$key]['val']=$val;
						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
					}
					else
					{
						$newarrayres[$key]['val']=utf8_encode($val);
						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
					}
				}
				else	// Autodetect format (UTF8 or ISO)
				{
					if (utf8_check($val))
					{
						$newarrayres[$key]['val']=$val;
						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
					}
					else
					{
						$newarrayres[$key]['val']=utf8_encode($val);
						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
					}
				}
			}

			$this->col=sizeof($newarrayres);
		}

		return $newarrayres;
	}
Ejemplo n.º 28
0
/**
 *	Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
 *	@param          str             String to clean
 *	@return         string          Cleaned string
 * 	@see    		dol_sanitizeFilename, dol_string_nospecial
 */
function dol_string_unaccent($str)
{
    if (utf8_check($str))
    {
        $string = rawurlencode($str);
        $replacements = array(
		'%C3%80' => 'A','%C3%81' => 'A',
		'%C3%88' => 'E','%C3%89' => 'E',
		'%C3%8C' => 'I','%C3%8D' => 'I',
		'%C3%92' => 'O','%C3%93' => 'O',
		'%C3%99' => 'U','%C3%9A' => 'U',
		'%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a',
		'%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
		'%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i',
		'%C3%B2' => 'o','%C3%B3' => 'o',
		'%C3%B9' => 'u','%C3%BA' => 'u'
		);
		$string=strtr($string, $replacements);
		return rawurldecode($string);
    }
    else
    {
        $string = strtr($str,
		"\xC0\xC1\xC2\xC3\xC5\xC7
	        \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
	        \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
	        \xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB
	        \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
	        \xF9\xFA\xFB\xFD\xFF",
		"AAAAAC
	        EEEEIIIIDN
	        OOOOOUUUY
	        aaaaaceeee
	        iiiidnooooo
	        uuuyy");
        $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
        return $string;
    }
}
Ejemplo n.º 29
0
 /**
  * Constructor
  */
 public function __construct()
 {
     global $INPUT;
     parent::__construct();
     // we load the config early to modify it a bit here
     $this->loadConfig();
     // additional information fields
     if (isset($this->conf['additional'])) {
         $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
         $this->conf['additional'] = explode(',', $this->conf['additional']);
     } else {
         $this->conf['additional'] = array();
     }
     // ldap extension is needed
     if (!function_exists('ldap_connect')) {
         if ($this->conf['debug']) {
             msg("AD Auth: PHP LDAP extension not found.", -1);
         }
         $this->success = false;
         return;
     }
     // Prepare SSO
     if (!empty($_SERVER['REMOTE_USER'])) {
         // make sure the right encoding is used
         if ($this->getConf('sso_charset')) {
             $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
         } elseif (!utf8_check($_SERVER['REMOTE_USER'])) {
             $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
         }
         // trust the incoming user
         if ($this->conf['sso']) {
             $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
             // we need to simulate a login
             if (empty($_COOKIE[DOKU_COOKIE])) {
                 $INPUT->set('u', $_SERVER['REMOTE_USER']);
                 $INPUT->set('p', 'sso_only');
             }
         }
     }
     // other can do's are changed in $this->_loadServerConfig() base on domain setup
     $this->cando['modName'] = true;
     $this->cando['modMail'] = true;
 }
Ejemplo n.º 30
0
 /**
  *  Load data into info_box_contents array to show array later.
  *
  *  @param	int		$max        	Maximum number of records to load
  *  @param	int		$cachedelay		Delay we accept for cache file
  *  @return	void
  */
 function loadBox($max = 5, $cachedelay = 3600)
 {
     global $user, $langs, $conf;
     $langs->load("boxes");
     $this->max = $max;
     // On recupere numero de param de la boite
     preg_match('/^([0-9]+) /', $this->paramdef, $reg);
     $site = $reg[1];
     // Create dir nor required
     // documents/externalrss is created by module activation
     // documents/externalrss/tmp is created by rssparser
     // Get RSS feed
     $url = @constant("EXTERNAL_RSS_URLRSS_" . $site);
     $rssparser = new RssParser($this->db);
     $result = $rssparser->parser($url, $this->max, $cachedelay, $conf->externalrss->dir_temp);
     // INFO on channel
     $description = $rssparser->getDescription();
     $link = $rssparser->getLink();
     $title = $langs->trans("BoxTitleLastRssInfos", $max, @constant("EXTERNAL_RSS_TITLE_" . $site));
     if ($result < 0 || !empty($rssparser->error)) {
         // Show warning
         $title .= " " . img_error($langs->trans("FailedToRefreshDataInfoNotUpToDate", $rssparser->getLastFetchDate() ? dol_print_date($rssparser->getLastFetchDate(), "dayhourtext") : $langs->trans("Unknown")));
         $this->info_box_head = array('text' => $title, 'limit' => 0);
     } else {
         $this->info_box_head = array('text' => $title, 'sublink' => $link, 'subtext' => $langs->trans("LastRefreshDate") . ': ' . ($rssparser->getLastFetchDate() ? dol_print_date($rssparser->getLastFetchDate(), "dayhourtext") : $langs->trans("Unknown")), 'subpicto' => 'object_bookmark');
     }
     // INFO on items
     $items = $rssparser->getItems();
     //print '<pre>'.print_r($items,true).'</pre>';
     $nbitems = count($items);
     for ($line = 0; $line < $max && $line < $nbitems; $line++) {
         $item = $items[$line];
         // Feed common fields
         $href = $item['link'];
         $title = urldecode($item['title']);
         $date = $item['date_timestamp'];
         // date will be empty if conversion into timestamp failed
         if ($rssparser->getFormat() == 'rss') {
             if (!$date && isset($item['pubdate'])) {
                 $date = $item['pubdate'];
             }
             if (!$date && isset($item['dc']['date'])) {
                 $date = $item['dc']['date'];
             }
             //$item['dc']['language']
             //$item['dc']['publisher']
         }
         if ($rssparser->getFormat() == 'atom') {
             if (!$date && isset($item['issued'])) {
                 $date = $item['issued'];
             }
             if (!$date && isset($item['modified'])) {
                 $date = $item['modified'];
             }
             //$item['issued']
             //$item['modified']
             //$item['atom_content']
         }
         if (is_numeric($date)) {
             $date = dol_print_date($date, "dayhour");
         }
         $isutf8 = utf8_check($title);
         if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') {
             $title = utf8_encode($title);
         } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
             $title = utf8_decode($title);
         }
         $title = preg_replace("/([[:alnum:]])\\?([[:alnum:]])/", "\\1'\\2", $title);
         // Gere probleme des apostrophes mal codee/decodee par utf8
         $title = preg_replace("/^\\s+/", "", $title);
         // Supprime espaces de debut
         $this->info_box_contents["{$href}"] = "{$title}";
         $tooltip = $title;
         $description = !empty($item['description']) ? $item['description'] : '';
         $isutf8 = utf8_check($description);
         if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') {
             $description = utf8_encode($description);
         } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
             $description = utf8_decode($description);
         }
         $description = preg_replace("/([[:alnum:]])\\?([[:alnum:]])/", "\\1'\\2", $description);
         $description = preg_replace("/^\\s+/", "", $description);
         $description = str_replace("\r\n", "", $description);
         $tooltip .= '<br>' . $description;
         $this->info_box_contents[$line][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, 'url' => $href, 'tooltip' => $tooltip, 'target' => 'newrss');
         $this->info_box_contents[$line][1] = array('td' => 'align="left"', 'text' => $title, 'url' => $href, 'tooltip' => $tooltip, 'maxlength' => 64, 'target' => 'newrss');
         $this->info_box_contents[$line][2] = array('td' => 'align="right" nowrap="1"', 'text' => $date);
     }
 }