xref: /plugin/sqlite/helper.php (revision db58e525166ab944e7a7720cadeff771e1b1e4aa)
1<?php
2/**
3 * DokuWiki Plugin sqlite (Helper Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr <gohr@cosmocode.de>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) die();
11
12if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
13if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
14if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
15
16if (!defined('DOKU_EXT_SQLITE')) define('DOKU_EXT_SQLITE', 'sqlite');
17if (!defined('DOKU_EXT_PDO')) define('DOKU_EXT_PDO', 'pdo');
18
19
20class helper_plugin_sqlite extends DokuWiki_Plugin {
21    var $db     = null;
22    var $dbname = '';
23    var $extension = null;
24    function getInfo() {
25        return confToHash(dirname(__FILE__).'plugin.info.txt');
26    }
27
28    /**
29     * constructor
30     */
31    function helper_plugin_sqlite(){
32
33      if(!$this->extension)
34      {
35        if (!extension_loaded('pdo_sqlite')) {
36            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
37            if(function_exists('dl')) @dl($prefix . 'pdo_sqlite.' . PHP_SHLIB_SUFFIX);
38        }
39
40        if(class_exists('pdo')){
41            $this->extension = DOKU_EXT_PDO;
42        }
43      }
44
45      if(!$this->extension)
46      {
47        if (!extension_loaded('sqlite')) {
48            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
49            if(function_exists('dl')) @dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
50        }
51
52        if(function_exists('sqlite_open')){
53           $this->extension = DOKU_EXT_SQLITE;
54        }
55      }
56
57      if(!$this->extension)
58
59      {
60        msg('SQLite & PDO SQLite support missing in this PHP install - plugin will not work',-1);
61      }
62    }
63
64    /**
65     * Initializes and opens the database
66     *
67     * Needs to be called right after loading this helper plugin
68     */
69    function init($dbname,$updatedir){
70        global $conf;
71
72        // check for already open DB
73        if($this->db){
74            if($this->dbname == $dbname){
75                // db already open
76                return true;
77            }
78            // close other db
79            if($this->extension == DOKU_EXT_SQLITE)
80            {
81              sqlite_close($this->db);
82            }
83            else
84            {
85              $this->db->close();
86            }
87            $this->db     = null;
88            $this->dbname = '';
89        }
90
91        $this->dbname = $dbname;
92
93        // Separate the database files to prevent not-requested autoupgrades.
94        if($this->extension == DOKU_EXT_SQLITE){
95            $fileextension = '.sqlite';
96        }else{
97            $fileextension = '.sqlite3';
98        }
99
100        $this->dbfile = $conf['metadir'].'/'.$dbname.$fileextension;
101
102        $init   = (!@file_exists($this->dbfile) || ((int) @filesize($this->dbfile)) < 3);
103
104        //first line tell the format of db file http://marc.info/?l=sqlite-users&m=109383875408202
105        $firstline=@file_get_contents($this->dbfile,false,null,0,15);
106
107        if($this->extension == DOKU_EXT_SQLITE)
108        {
109          if($firstline=='SQLite format 3'){
110              msg("SQLite: failed to open SQLite '".$this->dbname."' database (DB has a sqlite3 format instead of sqlite2 format.)",-1);
111              return false;
112          }
113
114          $error='';
115          $this->db = sqlite_open($this->dbfile, 0666, $error);
116          if(!$this->db){
117              msg("SQLite: failed to open SQLite '".$this->dbname."' database ($error)",-1);
118              return false;
119          }
120
121          // register our custom aggregate function
122          sqlite_create_aggregate($this->db,'group_concat',
123                                  array($this,'_sqlite_group_concat_step'),
124                                  array($this,'_sqlite_group_concat_finalize'), 2);
125        }
126        else
127        {
128          if($init){
129              $oldDbfile = substr($this->dbfile,0,-1);
130
131              if(@file_exists($oldDbfile)){
132                  $notfound_msg="SQLite: '".$this->dbname.$fileextension."' database not found. In the meta directory is '".$this->dbname.substr($fileextension,0,-1)."' available. ";
133
134                  $firstline=@file_get_contents($oldDbfile,false,null,0,15);
135                  if($firstline=='SQLite format 3'){
136                      msg($notfound_msg."PDO sqlite needs you rename manual the file extension to '.sqlite3' .",-1);
137                      return false;
138                  }else{
139                      msg($notfound_msg."PDO sqlite needs you upgrade manual this sqlite2 db to sqlite3 format.",-1);
140                      return false;
141                  }
142              }
143          }else{
144              if($firstline!='SQLite format 3'){
145                  msg("SQLite: failed to open SQLite '".$this->dbname."' database (DB has not a sqlite3 format.)",-1);
146                  return false;
147              }
148          }
149
150          $dsn = 'sqlite:'.$this->dbfile;
151
152          try {
153              $this->db = new PDO($dsn);
154          } catch (PDOException $e) {
155            msg("SQLite: failed to open SQLite '".$this->dbname."' database (".$e->getMessage().")",-1);
156              return false;
157          }
158          $this->db->sqliteCreateAggregate('group_concat',
159                                  array($this,'_pdo_group_concat_step'),
160                                  array($this,'_pdo_group_concat_finalize'));
161        }
162
163        $this->_updatedb($init,$updatedir);
164        return true;
165    }
166
167    /**
168     * Return the current Database Version
169     */
170    function _currentDBversion(){
171        $sql = "SELECT val FROM opts WHERE opt = 'dbversion';";
172        $res = $this->query($sql);
173        if(!$res) return false;
174        $row = $this->res2row($res,0);
175        return (int) $row['val'];
176    }
177    /**
178     * Update the database if needed
179     *
180     * @param bool   $init      - true if this is a new database to initialize
181     * @param string $updatedir - Database update infos
182     */
183    function _updatedb($init,$updatedir)
184    {
185        if($init){
186
187            $current = 0;
188        }else{
189            $current = $this->_currentDBversion();
190            if(!$current){
191                msg("SQLite: no DB version found. '".$this->dbname."' DB probably broken.",-1);
192                return false;
193            }
194        }
195
196        // in case of init, add versioning table
197        if($init){
198            if(!$this->_runupdatefile(dirname(__FILE__).'/db.sql',0)){
199                  msg("SQLite: '".$this->dbname."' database upgrade failed for version ", -1);
200                return false;
201            }
202        }
203
204        $latest  = (int) trim(io_readFile($updatedir.'/latest.version'));
205
206        // all up to date?
207        if($current >= $latest) return true;
208        for($i=$current+1; $i<=$latest; $i++){
209            $file = sprintf($updatedir.'/update%04d.sql',$i);
210            if(file_exists($file)){
211                if(!$this->_runupdatefile($file,$i)){
212                    msg("SQLite: '".$this->dbname."' database upgrade failed for version ".$i, -1);
213                    return false;
214                }
215            }
216        }
217        return true;
218    }
219
220    /**
221     * Updates the database structure using the given file to
222     * the given version.
223     */
224    function _runupdatefile($file,$version){
225        $sql  = io_readFile($file,false);
226
227        $sql = explode(";",$sql);
228        array_unshift($sql,'BEGIN TRANSACTION');
229        array_push($sql,"INSERT OR REPLACE INTO opts (val,opt) VALUES ($version,'dbversion')");
230        array_push($sql,"COMMIT TRANSACTION");
231
232        foreach($sql as $s){
233            $s = preg_replace('!^\s*--.*$!m', '', $s);
234            $s = trim($s);
235            if(!$s) continue;
236
237
238            $res = $this->query("$s;");
239            if ($res === false) {
240              if($this->extension == DOKU_EXT_SQLITE)
241              {
242                sqlite_query($this->db, 'ROLLBACK TRANSACTION');
243                return false;
244              }
245              else
246              {
247                return false;
248              }
249            }
250        }
251
252        return ($version == $this->_currentDBversion());
253    }
254
255    /**
256     * Emulate ALTER TABLE
257     *
258     * The ALTER TABLE syntax is parsed and then emulated using a
259     * temporary table
260     *
261     * @author <jon@jenseng.com>
262     * @link   http://code.jenseng.com/db/
263     * @author Andreas Gohr <gohr@cosmocode.de>
264     */
265    function _altertable($table,$alterdefs){
266
267        // load original table definition SQL
268        $result = $this->query("SELECT sql,name,type
269                                  FROM sqlite_master
270                                 WHERE tbl_name = '$table'
271                                   AND type = 'table'");
272
273        if(($result === false) || ($this->extension == DOKU_EXT_SQLITE && sqlite_num_rows($result)<=0)){
274            msg("ALTER TABLE failed, no such table '".hsc($table)."'",-1);
275            return false;
276        }
277
278        if($this->extension == DOKU_EXT_SQLITE )
279        {
280          $row = sqlite_fetch_array($result);
281        }
282        else
283        {
284           $row = $result->fetch(PDO::FETCH_ASSOC);
285        }
286
287        if($row === false){
288            msg("ALTER TABLE failed, table '".hsc($table)."' had no master data",-1);
289            return false;
290        }
291
292
293        // prepare temporary table SQL
294        $tmpname = 't'.time();
295        $origsql = trim(preg_replace("/[\s]+/"," ",
296                        str_replace(",",", ",
297                        preg_replace('/\)$/',' )',
298                        preg_replace("/[\(]/","( ",$row['sql'],1)))));
299        $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6);
300        $createindexsql = array();
301
302        // load indexes to reapply later
303        $result = $this->query("SELECT sql,name,type
304                                  FROM sqlite_master
305                                 WHERE tbl_name = '$table'
306                                   AND type = 'index'");
307        if(!$result){
308            $indexes = array();
309        }else{
310            $indexes = $this->res2arr($result);
311        }
312
313
314        $i = 0;
315        $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY);
316        $prevword = $table;
317        $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY);
318        $newcols = array();
319
320        for($i=0;$i<count($oldcols);$i++){
321            $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY);
322            $oldcols[$i] = $colparts[0];
323            $newcols[$colparts[0]] = $colparts[0];
324        }
325        $newcolumns = '';
326        $oldcolumns = '';
327        reset($newcols);
328        while(list($key,$val) = each($newcols)){
329            $newcolumns .= ($newcolumns?', ':'').$val;
330            $oldcolumns .= ($oldcolumns?', ':'').$key;
331        }
332        $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
333        $dropoldsql = 'DROP TABLE '.$table;
334        $createtesttableSQL = $createtemptableSQL;
335
336        foreach($defs as $def){
337            $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY);
338            $action = strtolower($defparts[0]);
339            switch($action){
340                case 'add':
341                    if(count($defparts) < 2){
342                        msg('ALTER TABLE: not enough arguments for ADD statement',-1);
343                        return false;
344                    }
345                    $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
346                    for($i=1;$i<count($defparts);$i++)
347                        $createtesttableSQL.=' '.$defparts[$i];
348                    $createtesttableSQL.=')';
349                    break;
350
351                case 'change':
352                    if(count($defparts) <= 3){
353                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error',-1);
354                        return false;
355                    }
356
357                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
358                        if($newcols[$defparts[1]] != $defparts[1]){
359                            msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
360                            return false;
361                        }
362                        $newcols[$defparts[1]] = $defparts[2];
363                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
364                        $insertval = '';
365                        for($i=2;$i<count($defparts);$i++)
366                            $insertval.=' '.$defparts[$i];
367                        if($nextcommapos)
368                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
369                        else
370                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
371                    } else {
372                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
373                        return false;
374                    }
375                    break;
376                case 'drop':
377                    if(count($defparts) < 2){
378                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error',-1);
379                        return false;
380                    }
381                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
382                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
383                        if($nextcommapos)
384                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
385                        else
386                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
387                        unset($newcols[$defparts[1]]);
388                    }else{
389                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
390                        return false;
391                    }
392                    break;
393                default:
394                    msg('ALTER TABLE: near "'.$prevword.'": syntax error',-1);
395                    return false;
396            }
397            $prevword = $defparts[count($defparts)-1];
398        }
399
400        // this block of code generates a test table simply to verify that the
401        // columns specifed are valid in an sql statement
402        // this ensures that no reserved words are used as columns, for example
403        $res = $this->query($createtesttableSQL);
404        if($res === false) return false;
405
406        $droptempsql = 'DROP TABLE '.$tmpname;
407        $res = $this->query($droptempsql);
408        if($res === false) return false;
409
410
411        $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
412        $newcolumns = '';
413        $oldcolumns = '';
414        reset($newcols);
415        while(list($key,$val) = each($newcols)){
416            $newcolumns .= ($newcolumns?', ':'').$val;
417            $oldcolumns .= ($oldcolumns?', ':'').$key;
418        }
419
420        $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
421
422        $res = $this->query($createtemptableSQL); //create temp table
423        if($res === false) return false;
424        $res = $this->query($copytotempsql); //copy to table
425        if($res === false) return false;
426        $res = $this->query($dropoldsql); //drop old table
427        if($res === false) return false;
428
429        $res = $this->query($createnewtableSQL); //recreate original table
430        if($res === false) return false;
431        $res = $this->query($copytonewsql); //copy back to original table
432        if($res === false) return false;
433
434        foreach($indexes as $index){ // readd indexes
435            $res = $this->query($index['sql']);
436            if($res === false) return false;
437        }
438
439        $res = $this->query($droptempsql); //drop temp table
440        if($res === false) return false;
441
442        return $res; // return a valid resource
443    }
444
445    /**
446     * Registers a User Defined Function for use in SQL statements
447     */
448    function create_function($function_name,$callback,$num_args){
449        if($this->extension == DOKU_EXT_SQLITE )
450        {
451          sqlite_create_function($this->db,$function_name,$callback,$num_args);
452        }
453        else
454        {
455          $this->db->sqliteCreateFunction($function_name,$callback,$num_args);
456        }
457    }
458
459    /**
460     * Execute a query with the given parameters.
461     *
462     * Takes care of escaping
463     *
464     * @param string $sql - the statement
465     * @param arguments...
466     */
467    function query(){
468        if(!$this->db) return false;
469
470        // get function arguments
471        $args = func_get_args();
472        $sql  = trim(array_shift($args));
473        $sql  = rtrim($sql,';');
474
475        if(!$sql){
476            msg('No SQL statement given',-1);
477            return false;
478        }
479
480        $argc = count($args);
481        if($argc > 0 && is_array($args[0])) {
482            $args = $args[0];
483            $argc = count($args);
484        }
485
486        // check number of arguments
487        if($argc < substr_count($sql,'?')){
488            msg('Not enough arguments passed for statement. '.
489                'Expected '.substr_count($sql,'?').' got '.
490                $argc.' - '.hsc($sql),-1);
491            return false;
492        }
493
494        // explode at wildcard, then join again
495        $parts = explode('?',$sql,$argc+1);
496        $args  = array_map(array($this,'quote_string'),$args);
497        $sql   = '';
498
499        while( ($part = array_shift($parts)) !== null ){
500            $sql .= $part;
501            $sql .= array_shift($args);
502        }
503
504        // intercept ALTER TABLE statements
505        $match = null;
506        if(preg_match('/^ALTER\s+TABLE\s+([\w\.]+)\s+(.*)/i',$sql,$match)){
507            return $this->_altertable($match[1],$match[2]);
508        }
509
510        // execute query
511        $err = '';
512        if($this->extension == DOKU_EXT_SQLITE )
513        {
514          $res = @sqlite_query($this->db,$sql,SQLITE_ASSOC,$err);
515          if($err){
516              msg($err.':<br /><pre>'.hsc($sql).'</pre>',-1);
517              return false;
518          }elseif(!$res){
519              msg(sqlite_error_string(sqlite_last_error($this->db)).
520                  ':<br /><pre>'.hsc($sql).'</pre>',-1);
521              return false;
522          }
523        }
524        else
525        {
526          $res = $this->db->query($sql);
527
528          if(!$res){
529            $err = $this->db->errorInfo();
530              msg($err[2].':<br /><pre>'.hsc($sql).'</pre>',-1);
531              return false;
532          }
533        }
534        return $res;
535    }
536
537    /**
538     * Returns a complete result set as array
539     */
540    function res2arr($res){
541        $data = array();
542        if($this->extension == DOKU_EXT_SQLITE )
543        {
544          if(!sqlite_num_rows($res)) return $data;
545          sqlite_rewind($res);
546          while(($row = sqlite_fetch_array($res, SQLITE_ASSOC)) !== false){
547              $data[] = $row;
548          }
549        }
550        else
551        {
552          if(!$res) return $data;
553          $data = $res->fetchAll(PDO::FETCH_ASSOC);
554        }
555        return $data;
556    }
557
558    /**
559     * Return the wanted row from a given result set as
560     * associative array
561     */
562    function res2row($res,$rownum=0){
563        if($this->extension == DOKU_EXT_SQLITE )
564        {
565          if(!@sqlite_seek($res,$rownum)){
566              return false;
567          }
568          return sqlite_fetch_array($res, SQLITE_ASSOC);
569        }
570        else
571        {
572          if(!$res) return false;
573
574          return $res->fetch(PDO::FETCH_ASSOC,PDO::FETCH_ORI_ABS,$rownum);
575        }
576    }
577
578    /**
579     * Return the first value from the first row.
580     */
581    function res2single($res)
582    {
583      if($this->extension == DOKU_EXT_SQLITE )
584      {
585        return sqlite_fetch_single($res);
586      }
587      else
588      {
589        if(!$res) return false;
590
591        $data = $res->fetch(PDO::FETCH_NUM,PDO::FETCH_ORI_ABS,0);
592        if(!count($data))
593        {
594          return false;
595        }
596        return $data[0];
597      }
598    }
599
600    /**
601     * Join the given values and quote them for SQL insertion
602     */
603    function quote_and_join($vals,$sep=',') {
604        $vals = array_map(array('helper_plugin_sqlite','quote_string'),$vals);
605        return join($sep,$vals);
606    }
607
608    /**
609     * Run sqlite_escape_string() on the given string and surround it
610     * with quotes
611     */
612    function quote_string($string){
613      if($this->extension == DOKU_EXT_SQLITE )
614      {
615        return "'".sqlite_escape_string($string)."'";
616      }
617      else
618      {
619        return $this->db->quote($string);
620      }
621    }
622
623
624    /**
625     * Escape string for sql
626     */
627    function escape_string($str)
628    {
629      if($this->extension == DOKU_EXT_SQLITE )
630      {
631        return sqlite_escape_string($str);
632      }
633      else
634      {
635        return trim($this->db->quote($str), "'");
636      }
637    }
638
639
640
641    /**
642    * Aggregation function for SQLite
643    *
644    * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
645    */
646    function _sqlite_group_concat_step(&$context, $string, $separator = ',') {
647         $context['sep'] = $separator;
648         $context['data'][] = $string;
649    }
650
651    /**
652    * Aggregation function for SQLite
653    *
654    * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
655    */
656    function _sqlite_group_concat_finalize(&$context) {
657         $context['data'] = array_unique($context['data']);
658         return join($context['sep'],$context['data']);
659    }
660
661
662    /**
663     * Aggregation function for SQLite via PDO
664     *
665     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
666     */
667    function _pdo_group_concat_step(&$context, $rownumber, $string, $separator = ',') {
668         if(is_null($context))
669         {
670           $context = array(
671             'sep'  => $separator,
672             'data' => array()
673             );
674         }
675
676         $context['data'][] = $string;
677         return $context;
678    }
679
680     /**
681     * Aggregation function for SQLite via PDO
682     *
683     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
684     */
685    function _pdo_group_concat_finalize(&$context, $rownumber)
686    {
687        if(!is_array($context))
688        {
689          return null;
690        }
691        $context['data'] = array_unique($context['data']);
692        return join($context['sep'],$context['data']);
693    }
694
695    /**
696     * Keep separate instances for every call to keep database connections
697     */
698    function isSingleton() {
699         return false;
700    }
701
702     /**
703     * fetch the next row as zero indexed array
704     */
705    function res_fetch_array($res)
706    {
707      if($this->extension == DOKU_EXT_SQLITE )
708      {
709        return sqlite_fetch_array($res, SQLITE_NUM);
710      }
711      else
712      {
713        if(!$res) return false;
714
715        return $res->fetch(PDO::FETCH_NUM);
716      }
717    }
718
719
720    /**
721     * fetch the next row as assocative array
722     */
723    function res_fetch_assoc($res)
724    {
725      if($this->extension == DOKU_EXT_SQLITE )
726      {
727        return sqlite_fetch_array($res, SQLITE_ASSOC);
728      }
729      else
730      {
731        if(!$res) return false;
732
733        return $res->fetch(PDO::FETCH_ASSOC);
734      }
735    }
736
737
738    /**
739
740     * Count the number of records in result
741     *
742     * This function is really inperformant in PDO and should be avoided!
743     */
744    function res2count($res) {
745      if($this->extension == DOKU_EXT_SQLITE )
746      {
747        return sqlite_num_rows($res);
748      }
749      else
750      {
751        if(!$res) return false;
752
753        return count($res->fetch(PDO::FETCH_NUM));
754
755      }
756    }
757
758
759    /**
760    * Count the number of records changed last time
761    */
762    function countChanges($db, $res)
763    {
764      if($this->extension == DOKU_EXT_SQLITE )
765      {
766        return sqlite_changes($db);
767      }
768      else
769      {
770        if(!$res) return false;
771
772        return $res->rowCount();
773      }
774    }
775}
776
777// vim:ts=4:sw=4:et:enc=utf-8:
778