source: extensions/AMetaData/amd_root.class.inc.php @ 15343

Last change on this file since 15343 was 15343, checked in by grum, 12 years ago

feature:2637 - Compatibility with Piwigo 2.4

  • Property svn:executable set to *
File size: 22.3 KB
Line 
1<?php
2/*
3 * -----------------------------------------------------------------------------
4 * Plugin Name: Advanced MetaData
5 * -----------------------------------------------------------------------------
6 * Author     : Grum
7 *   email    : grum@piwigo.org
8 *   website  : http://photos.grum.fr
9 *   PWG user : http://forum.piwigo.org/profile.php?id=3706
10 *
11 *   << May the Little SpaceFrog be with you ! >>
12 *
13 * -----------------------------------------------------------------------------
14 *
15 * See main.inc.php for release information
16 *
17 * AMD_install : classe to manage plugin install
18 * ---------------------------------------------------------------------------
19 */
20
21if (!defined('PHPWG_ROOT_PATH')) { die('Hacking attempt!'); }
22
23include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/CommonPlugin.class.inc.php');
24include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCCss.class.inc.php');
25include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCRequestBuilder.class.inc.php');
26
27include_once('amd_jpegmetadata.class.inc.php');
28include_once(JPEG_METADATA_DIR."Common/L10n.class.php");
29include_once(JPEG_METADATA_DIR."TagDefinitions/XmpTags.class.php");
30
31class AMD_root extends CommonPlugin
32{
33  protected $css;   //the css object
34  protected $jpegMD;
35
36  public function __construct($prefixeTable, $filelocation)
37  {
38    global $user;
39    $this->setPluginName("Advanced MetaData");
40    $this->setPluginNameFiles("amd");
41    parent::__construct($prefixeTable, $filelocation);
42
43    $tableList=array(
44      'used_tags',
45      'images_tags',
46      'images',
47      'selected_tags',
48      'groups_names',
49      'groups',
50      'user_tags_label',
51      'user_tags_def',
52      'tags_values');
53    $this->setTablesList($tableList);
54
55    $this->css = new GPCCss(dirname($this->getFileLocation()).'/'.$this->getPluginNameFiles().".css");
56    $this->jpegMD=new AMD_JpegMetaData();
57
58    if(isset($user['language']))
59    {
60      L10n::setLanguage($user['language']);
61    }
62  }
63
64  public function __destruct()
65  {
66    unset($this->jpegMD);
67    unset($this->css);
68    //parent::__destruct();
69  }
70
71  /* ---------------------------------------------------------------------------
72  common AIP & PIP functions
73  --------------------------------------------------------------------------- */
74
75  /* this function initialize var $config with default values */
76  public function initConfig()
77  {
78    $this->config=array(
79      // options set by the plugin interface - don't modify them manually
80      'amd_GetListTags_OrderType' => "tag",
81      'amd_GetListTags_FilterType' => "magic",
82      'amd_GetListTags_ExcludeUnusedTag' => "y",
83      'amd_GetListTags_SelectedTagOnly' => "n",
84      'amd_GetListImages_OrderType' => "value",
85      'amd_AllPicturesAreAnalyzed' => "n",
86      'amd_FillDataBaseContinuously' => "y",
87      'amd_FillDataBaseIgnoreSchemas' => array(),
88      'amd_InterfaceMode' => "advanced",    // 'advanced' or 'basic'
89
90      // theses options can be set manually
91      'amd_NumberOfItemsPerRequest' => 25,
92      'amd_DisplayWarningsMessageStatus' => "y",
93      'amd_DisplayWarningsMessageUpdate' => "y",
94      'amd_FillDataBaseExcludeTags' => array(),
95      'amd_FillDataBaseExcludeFilters' => array(),
96    );
97    /*
98     * ==> amd_FillDataBaseExcludeTags : array of tagId
99     *     the listed tag are completely excluded by the plugin, as they don't
100     *     exist
101     *     for each tagId you can use generic char as the LIKE sql operator
102     *      array('xmp.%', 'exif.maker.%')
103     *        -> exclude all XMP and EXIF MAKER tags
104     *
105     * ==> amd_FillDataBaseExcludeFilters : array of filterValue
106     *     if you exclude all the xmp tag you probably want to exclude everything
107     *     displaying 'xmp'
108     *     array('exif.maker',
109     *           'exif',
110     *           'iptc',
111     *           'xmp',
112     *           'magic',
113     *           'com')
114     *
115     * ==> amd_DisplayWarningsMessageStatus : 'y' or 'n'
116     *     amd_DisplayWarningsMessageUpdate
117     *     you can disable warnings messages displayed on the database status&update
118     *     page
119     */
120  }
121
122  public function loadConfig()
123  {
124    parent::loadConfig();
125  }
126
127  public function initEvents()
128  {
129    parent::initEvents();
130  }
131
132  public function getAdminLink($mode='')
133  {
134    if($mode=='ajax')
135    {
136      return('plugins/'.basename(dirname($this->getFileLocation())).'/amd_ajax.php');
137    }
138    else
139    {
140      return(parent::getAdminLink());
141    }
142  }
143
144  /**
145   *
146   */
147  protected function configForTemplate()
148  {
149    global $template;
150
151    $template->assign('amdConfig', $this->config);
152  }
153
154  /**
155   * returns the number of pictures analyzed
156   *
157   * @return Integer
158   */
159  protected function getNumOfPictures()
160  {
161    $numOfPictures=0;
162    $sql="SELECT COUNT(imageId) FROM ".$this->tables['images']."
163            WHERE analyzed='y';";
164    $result=pwg_query($sql);
165    if($result)
166    {
167      while($row=pwg_db_fetch_row($result))
168      {
169        $numOfPictures=$row[0];
170      }
171    }
172    return($numOfPictures);
173  }
174
175
176  /**
177   * this function randomly choose a picture in the list of pictures not
178   * analyzed, and analyze it
179   *
180   */
181  public function doRandomAnalyze()
182  {
183    $sql="SELECT tai.imageId, ti.path FROM ".$this->tables['images']." tai
184            LEFT JOIN ".IMAGES_TABLE." ti ON tai.imageId = ti.id
185          WHERE tai.analyzed = 'n'
186          ORDER BY RAND() LIMIT 1;";
187    $result=pwg_query($sql);
188    if($result)
189    {
190      // $path = path of piwigo's on the server filesystem
191      $path=dirname(dirname(dirname(__FILE__)));
192
193      while($row=pwg_db_fetch_assoc($result))
194      {
195        $this->analyzeImageFile($path."/".$row['path'], $row['imageId']);
196      }
197
198      $this->makeStatsConsolidation();
199    }
200  }
201
202
203  /**
204   * this function analyze tags from a picture, and insert the result into the
205   * database
206   *
207   * NOTE : only implemented tags are analyzed and stored
208   *
209   * @param String $fileName : filename of picture to analyze
210   * @param Integer $imageId : id of image in piwigo's database
211   * @param Boolean $loaded  : default = false
212   *                            WARNING
213   *                            if $loaded is set to TRUE, the function assume
214   *                            that the metadata have been alreay loaded
215   *                            do not use the TRUE value if you are not sure
216   *                            of the consequences
217   */
218  protected function analyzeImageFile($fileName, $imageId, $loaded=false)
219  {
220    $schemas=array_flip($this->config['amd_FillDataBaseIgnoreSchemas']);
221    /*
222     * the JpegMetaData object is instancied in the constructor
223     */
224    if(!$loaded)
225    {
226      $this->jpegMD->load(
227        $fileName,
228        Array(
229          'filter' => AMD_JpegMetaData::TAGFILTER_IMPLEMENTED,
230          'optimizeIptcDateTime' => true,
231          'exif' => !isset($schemas['exif']),
232          'iptc' => !isset($schemas['iptc']),
233          'xmp' => !isset($schemas['xmp']),
234          'magic' => !isset($schemas['magic']),
235          'com' => !isset($schemas['com']),
236        )
237      );
238    }
239
240    //$sqlInsert="";
241    $massInsert=array();
242    $nbTags=0;
243    foreach($this->jpegMD->getTags() as $key => $val)
244    {
245      $value=$val->getLabel();
246
247      if($val->isTranslatable())
248        $translatable="y";
249      else
250        $translatable="n";
251
252      if($value instanceof DateTime)
253      {
254        $value=$value->format("Y-m-d H:i:s");
255      }
256      elseif(is_array($value))
257      {
258        /*
259         * array values are stored in a serialized string
260         */
261        $value=serialize($value);
262      }
263
264      $sql="SELECT numId FROM ".$this->tables['used_tags']." WHERE tagId = '$key'";
265
266      $result=pwg_query($sql);
267      if($result)
268      {
269        $numId=-1;
270        while($row=pwg_db_fetch_assoc($result))
271        {
272          $numId=$row['numId'];
273        }
274
275        if($numId>0)
276        {
277          $nbTags++;
278          //if($sqlInsert!="") $sqlInsert.=", ";
279          //$sqlInsert.="($imageId, '$numId', '".addslashes($value)."')";
280          $massInsert[]="('$imageId', '$numId', '".pwg_db_real_escape_string($value)."') ";
281        }
282      }
283    }
284
285    if(count($massInsert)>0)
286    {
287      $sql="REPLACE INTO ".$this->tables['images_tags']." (imageId, numId, value) VALUES ".implode(", ", $massInsert).";";
288      pwg_query($sql);
289    }
290    //mass_inserts($this->tables['images_tags'], array('imageId', 'numId', 'value'), $massInsert);
291
292    $sql="UPDATE ".$this->tables['images']."
293            SET analyzed = 'y', nbTags=".$nbTags."
294            WHERE imageId=$imageId;";
295    pwg_query($sql);
296
297    unset($massInsert);
298
299    return("$imageId=$nbTags;");
300  }
301
302
303  /**
304   * returns the userDefined tag for one image (without searching in the
305   * database)
306   *
307   * @param Array $numId : array of userDefined numId to get
308   * @param Array $values : array of existing tag for the images
309   * @return Array : associated array of numId=>value
310   */
311  protected function pictureGetUserDefinedTags($listId, $values)
312  {
313    if(count($listId)==0 or count($values)==0) return(array());
314
315    $listIds=implode(',', $listId);
316    $rules=array();
317    $returned=array();
318
319    $sql="SELECT numId, defId, parentId, `order`, `type`, value, conditionType, conditionValue
320          FROM ".$this->tables['user_tags_def']."
321          WHERE numId IN ($listIds)
322          ORDER BY numId, parentId, `order`;";
323    $result=pwg_query($sql);
324    if($result)
325    {
326      while($row=pwg_db_fetch_assoc($result))
327      {
328        $rules[$row['numId']][$row['parentId']][$row['defId']]=$row;
329      }
330    }
331
332    foreach($listId as $numId)
333    {
334      $returned[$numId]=$this->buildUserDefinedTagConditionRule(0, $values, $rules[$numId]);
335    }
336
337    return($returned);
338  }
339
340  /**
341   *
342   * @param String $id : id of the metadata to build
343   */
344  protected function buildUserDefinedTags($id)
345  {
346    $num=0;
347    $sql="SELECT GROUP_CONCAT(DISTINCT value ORDER BY value SEPARATOR ',')
348          FROM ".$this->tables['user_tags_def']."
349          WHERE `type`='C' or `type`='M'
350            AND numId='$id'";
351    $result=pwg_query($sql);
352    if($result)
353    {
354      // get the list of tags used to build the user defined tag
355      $list='';
356      while($row=pwg_db_fetch_row($result))
357      {
358        $list=$row[0];
359      }
360
361      $sql="(SELECT ait.imageId, ait.numId, ait.value
362             FROM ".$this->tables['images_tags']." ait
363             WHERE ait.numId IN ($list)
364            )
365            UNION
366            (SELECT pai.imageId, 0, ''
367            FROM ".$this->tables['images']." pai)
368            ORDER BY imageId, numId";
369      $result=pwg_query($sql);
370      if($result)
371      {
372        //build a list of properties for each image
373        $images=array();
374        while($row=pwg_db_fetch_assoc($result))
375        {
376          if(!array_key_exists($row['imageId'], $images))
377          {
378            $images[$row['imageId']]=array();
379          }
380          $images[$row['imageId']][$row['numId']]=$row['value'];
381        }
382
383        //load the rules
384        $sql="SELECT defId, parentId, `order`, `type`, value, conditionType, conditionValue
385              FROM ".$this->tables['user_tags_def']."
386              WHERE numId='$id'
387              ORDER BY parentId, `order`;";
388        $result=pwg_query($sql);
389        if($result)
390        {
391          $rules=array();
392          while($row=pwg_db_fetch_assoc($result))
393          {
394            $rules[$row['parentId']][$row['defId']]=$row;
395          }
396
397          $inserts=array();
398          // calculate tag values for each image
399          foreach($images as $key=>$val)
400          {
401            $buildValue=$this->buildUserDefinedTag($key, $val, $id, $rules);
402
403            if(!is_null($buildValue['value']))
404            {
405              $buildValue['value']=addslashes($buildValue['value']);
406              $inserts[]=$buildValue;
407              $num++;
408            }
409          }
410
411          mass_inserts($this->tables['images_tags'], array('imageId', 'numId', 'value'), $inserts);
412        }
413      }
414    }
415    return($num);
416  }
417
418
419  /**
420   * build the userDefined tag for an image
421   *
422   * @param String $imageId : id of the image
423   * @param Array $values : array of existing tag for the images
424   * @param String $numId : id of the metadata to build
425   * @param Array $rules  : rules to apply to build the metadata
426   */
427  protected function buildUserDefinedTag($imageId, $values, $numId, $rules)
428  {
429    $returned=array(
430      'imageId' => $imageId,
431      'numId' => $numId,
432      'value' => $this->buildUserDefinedTagConditionRule(0, $values, $rules)
433    );
434
435    return($returned);
436  }
437
438
439  /**
440   * build the userDefined tag for an image
441   *
442   * @param String $imageId : id of the image
443   * @param Array $values : array of existing tag for the images
444   * @param String $numId : id of the metadata to build
445   * @param Array $rules  : rules to apply to build the metadata
446   */
447  protected function buildUserDefinedTagConditionRule($parentId, $values, $rules)
448  {
449    $null=true;
450    $returned='';
451    foreach($rules[$parentId] as $rule)
452    {
453      switch($rule['type'])
454      {
455        case 'T':
456          $returned.=$rule['value'];
457          $null=false;
458          break;
459        case 'M':
460          if(isset($values[$rule['value']]))
461          {
462            $returned.=$values[$rule['value']];
463            $null=false;
464          }
465          break;
466        case 'C':
467          $ok=false;
468          switch($rule['conditionType'])
469          {
470            case 'E':
471              if(isset($values[$rule['value']])) $ok=true;
472              break;
473            case '!E':
474              if(!isset($values[$rule['value']])) $ok=true;
475              break;
476            case '=':
477              if(isset($values[$rule['value']]) and
478                 $values[$rule['value']]==$rule['conditionValue']) $ok=true;
479              break;
480            case '!=':
481              if(isset($values[$rule['value']]) and
482                 $values[$rule['value']]!=$rule['conditionValue']) $ok=true;
483              break;
484            case '%':
485              if(isset($values[$rule['value']]) and
486                 preg_match('/'.$rule['conditionValue'].'/i', $values[$rule['value']])) $ok=true;
487              break;
488            case '!%':
489              if(isset($values[$rule['value']]) and
490                 !preg_match('/'.$rule['conditionValue'].'/i', $values[$rule['value']])) $ok=true;
491              break;
492            case '^%':
493              if(isset($values[$rule['value']]) and
494                 preg_match('/^'.$rule['conditionValue'].'/i', $values[$rule['value']])) $ok=true;
495              break;
496            case '!^%':
497              if(isset($values[$rule['value']]) and
498                 !preg_match('/^'.$rule['conditionValue'].'/i', $values[$rule['value']])) $ok=true;
499              break;
500            case '$%':
501              if(isset($values[$rule['value']]) and
502                 preg_match('/'.$rule['conditionValue'].'$/i', $values[$rule['value']])) $ok=true;
503              break;
504            case '!$%':
505              if(isset($values[$rule['value']]) and
506                 !preg_match('/'.$rule['conditionValue'].'$/i', $values[$rule['value']])) $ok=true;
507              break;
508          }
509          if($ok)
510          {
511            $subRule=$this->buildUserDefinedTagConditionRule($rule['defId'], $values, $rules);
512            if(!is_null($subRule))
513            {
514              $null=false;
515              $returned.=$subRule;
516            }
517          }
518          break;
519      }
520    }
521    if($null)
522    {
523      return(null);
524    }
525    return($returned);
526  }
527
528
529
530
531  /**
532   * do some consolidations on database to optimize other requests
533   *
534   */
535  protected function makeStatsConsolidation()
536  {
537    // reset numbers
538    $sql="UPDATE ".$this->tables['used_tags']." ut
539          SET ut.numOfImg = 0;";
540    pwg_query($sql);
541
542    $sql="UPDATE ".$this->tables['images']." pai
543          SET pai.nbTags = 0;";
544    pwg_query($sql);
545
546
547    // count number of images per tag
548    $sql="UPDATE ".$this->tables['used_tags']." ut,
549            (SELECT COUNT(DISTINCT imageId) AS nb, numId
550              FROM ".$this->tables['images_tags']."
551              GROUP BY numId) nb
552          SET ut.numOfImg = nb.nb
553          WHERE ut.numId = nb.numId;";
554    pwg_query($sql);
555
556    //count number of tags per images
557    $sql="UPDATE ".$this->tables['images']." pai,
558            (SELECT COUNT(DISTINCT numId) AS nb, imageId
559              FROM ".$this->tables['images_tags']."
560              GROUP BY imageId) nb
561          SET pai.nbTags = nb.nb
562          WHERE pai.imageId = nb.imageId;";
563    pwg_query($sql);
564
565
566    $sql="SELECT COUNT(imageId) AS nb
567          FROM ".$this->tables['images']."
568          WHERE analyzed = 'n';";
569    $result=pwg_query($sql);
570    if($result)
571    {
572      while($row=pwg_db_fetch_assoc($result))
573      {
574        $this->config['amd_AllPicturesAreAnalyzed']=($row['nb']==0)?'y':'n';
575      }
576
577    }
578
579    $sql="UPDATE ".$this->tables['used_tags']." ut
580          SET ut.newFromLastUpdate = 'n'
581          WHERE ut.newFromLastUpdate = 'y';";
582    pwg_query($sql);
583
584    $this->saveConfig();
585  }
586
587  /**
588   * This function :
589   *  - convert arrays (stored as a serialized string) into human readable string
590   *  - translate value in user language (if value is translatable)
591   *
592   * @param String $value         : value to prepare
593   * @param Boolean $translatable : set to tru if the value can be translated in
594   *                                the user language
595   * @param String $separator     : separator for arrays items
596   * @return String               : the value prepared
597   */
598  static public function prepareValueForDisplay($value, $translatable=true, $separator=", ")
599  {
600    global $user;
601
602    if(preg_match('/^a:\d+:\{.*\}$/is', $value))
603    {
604      // $value is a serialized array
605      $tmp=unserialize($value);
606
607      if(count($tmp)==0)
608      {
609        return(L10n::get("Unknown"));
610      }
611
612      if(array_key_exists("computed", $tmp) and array_key_exists("detail", $tmp))
613      {
614        /* keys 'computed' and 'detail' are present
615         *
616         * assume this is the 'exif.exif.Flash' metadata and return the computed
617         * value only
618         */
619        return(L10n::get($tmp['computed']));
620      }
621      elseif(array_key_exists("type", $tmp) and array_key_exists("values", $tmp))
622      {
623        /* keys 'computed' and 'detail' are present
624         *
625         * assume this is an Xmp 'ALT', 'BAG' or 'SEQ' metadata and return the
626         * values only
627         */
628        if($tmp['type']=='alt')
629        {
630          /* 'ALT' structure
631           *
632           * ==> assuming the structure is used only for multi language values
633           *
634           * Array(
635           *    'type'   => 'ALT'
636           *    'values' =>
637           *        Array(
638           *            Array(
639           *                'type'  => Array(
640           *                            'name'  =>'xml:lang',
641           *                            'value' => ''           // language code
642           *                           )
643           *               'value' => ''         //value in the defined language
644           *            ),
645           *
646           *            Array(
647           *                // data2
648           *            ),
649           *
650           *        )
651           * )
652           */
653          $tmp=XmpTags::getAltValue($tmp, $user['language']);
654          if(trim($tmp)=="") $tmp="(".L10n::get("not defined").")";
655
656          return($tmp);
657        }
658        else
659        {
660          /* 'SEQ' or 'BAG' structure
661           *
662           *  Array(
663           *    'type'   => 'XXX',
664           *    'values' => Array(val1, val2, .., valN)
665           *  )
666           */
667          $tmp=$tmp['values'];
668
669          if(trim(implode("", $tmp))=="")
670          {
671            return("(".L10n::get("not defined").")");
672          }
673        }
674      }
675
676
677      foreach($tmp as $key=>$val)
678      {
679        if(is_array($val))
680        {
681          if($translatable)
682          {
683            foreach($val as $key2=>$val2)
684            {
685              $tmp[$key][$key2]=L10n::get($val2);
686            }
687            if(count($val)>0)
688            {
689              $tmp[$key]="[".implode($separator, $val)."]";
690            }
691            else
692            {
693              unset($tmp[$key]);
694            }
695          }
696        }
697        else
698        {
699          if($translatable)
700          {
701            $tmp[$key]=L10n::get($val);
702          }
703        }
704      }
705      return(implode($separator, $tmp));
706    }
707    elseif(preg_match('/\d{1,3}°\s\d{1,2}\'\s(\d{1,2}\.{0,1}\d{0,2}){0,1}.,\s(north|south|east|west)$/i', $value))
708    {
709      /* \d{1,3}°\s\d{1,2}\'\s(\d{1,2}\.{0,1}\d{0,2}){0,1}.
710       *
711       * keys 'coord' and 'card' are present
712       *
713       * assume this is a GPS coordinate
714       */
715        return(preg_replace(
716          Array('/, north$/i', '/, south$/i', '/, east$/i', '/, west$/i'),
717          Array(" ".L10n::get("North"), " ".L10n::get("South"), " ".L10n::get("East"), " ".L10n::get("West")),
718          $value)
719        );
720    }
721    else
722    {
723      if(trim($value)=="")
724      {
725        return("(".L10n::get("not defined").")");
726      }
727
728      if(strpos($value, "|")>0)
729      {
730        $value=explode("|", $value);
731        if($translatable)
732        {
733          foreach($value as $key=>$val)
734          {
735            $value[$key]=L10n::get($val);
736          }
737        }
738        return(implode("", $value));
739      }
740
741      if($translatable)
742      {
743        return(L10n::get($value));
744      }
745      return($value);
746    }
747  }
748
749
750} // amd_root  class
751
752
753
754Class AMD_functions {
755  /**
756   *  return all HTML&JS code necessary to display a dialogbox to choose
757   *  a metadata
758   */
759  static public function dialogBoxMetadata()
760  {
761    global $template, $prefixeTable;
762
763    $tables=array(
764        'used_tags' => $prefixeTable.'amd_used_tags',
765        'selected_tags' => $prefixeTable.'amd_selected_tags',
766    );
767
768    $template->set_filename('metadata_choose',
769                  dirname(__FILE__).'/templates/amd_dialog_metadata_choose.tpl');
770
771    $datas=array(
772      'urlRequest' => 'plugins/'.basename(dirname(__FILE__)).'/amd_ajax.php',
773      'tagList' => array(),
774    );
775
776    /*
777     * build tagList
778     */
779    $sql="SELECT ut.name, ut.numId, ut.tagId
780          FROM ".$tables['used_tags']." ut
781            JOIN ".$tables['selected_tags']." st ON st.tagId = ut.tagId
782          ORDER BY tagId";
783    $result=pwg_query($sql);
784    if($result)
785    {
786      while($row=pwg_db_fetch_assoc($result))
787      {
788        $datas['tagList'][]=Array(
789          'tagId' => $row['tagId'],
790          'name'  => L10n::get($row['name']),
791          'numId' => $row['numId']
792        );
793      }
794    }
795
796    $template->assign('datas', $datas);
797    unset($data);
798
799    return($template->parse('metadata_choose', true));
800  }
801}
802
803
804
805?>
Note: See TracBrowser for help on using the repository browser.