<?php
define( 'WS_WEB', true );
require_once('WSInit.php');
require_once('WikiQuery.php');

function getUploadInfo($field, $row) {
  global $wq;
  
  $html= '';
  
  $html.= $wq->makeLink($row["img_name"], NS_IMAGE, false);
  
  $html.= "<br/>";
  $html.= "<small>";
  $html.= htmlspecialchars($row["img_major_mime"].'/'.$row["img_minor_mime"]).", ";
  if ($row['img_width']>0 || $row['img_height']>0 ) $html.= htmlspecialchars($row["img_width"].'x'.$row["img_height"]).", ";
  $html.= ceil($row["img_size"]/1024)."&thinsp;KB";
  $html.= " (";
  $u= "CheckUsage.php?i=".urlencode($row["img_name"])."&amp;w=_100000";
  $html.= "<i><a href='$u'>usage</a></i>";
  $html.= ") ";
  $html.= "<br/>";
  $html.= $wq->makeLink($row["img_user_text"], NS_USER, false);
  $html.= " (";
  $p= "img_user_text=".urlencode($row["img_user_text"])
      ."&amp;wikifam=".urlencode($wq->wikiSelector->selected)
      ."&amp;wikilang=".urlencode($wq->wikiSelector->lang);
  $u= "Gallery.php?$p";
  $html.= "<i><a href='$u'>gallery</a></i>";
  $html.= " / ";
  $u= "OrphanImages.php?$p";
  $html.= "<i><a href='$u'>orphans</a></i>";
  $html.= " / ";
  $u= "UntaggedImages.php?$p";
  $html.= "<i><a href='$u'>untagged</a></i>";
  $html.= ") ";
  $html.= "<br/>";
  $html.= $wq->makeDate($row["img_timestamp"]);
  $html.= "</small>";
  
  return $html;
}

function getThumbInfo($field, &$row) {
  global $wq;

  $html= $wq->wiki->getThumbnailHTML($row);
  
  return $html;
}

function getTagInfo($field, $row) {
  global $wq;

  initImageInfo($row);

      $t= preg_replace( '~<!--.*?-->|<nowiki>.*?</nowiki>~is', '', $row['_text'] );
      preg_match_all( TEMPLATE_PATTERN, $t, $templates, PREG_PATTERN_ORDER );
      $templates= $templates[1];
      $templates= array_unique($templates);
      
      $html= '';
      $c= 0;
      
      foreach ( $templates as $tmpl ) {
              if ($html) $html.= ', ';
              
              if (preg_match('/^:/',$tmpl)) {
                $ns= '';
                $title= $tmpl;
                $showns= false;
              }
              else {  
                $l= $wq->wiki->makeLinkEntry($tmpl);
                if ($l['namespace']) {
                  $ns= $l['namespace'];
                  $title= $l['link'];
                  $showns= true;
                }
                else {
                  $ns= $wq->wiki->getNSText(NS_TEMPLATE);
                  $title= $tmpl;
                  $showns= false;
                }
              }
      
              $lnk= $wq->makeLink($title,$ns,$showns);
              
              if ($wq->wiki->hasTemplateClasses()) {
                  $cls= $wq->wiki->getTemplateClass($tmpl);
                  if (!$cls) $cls= 'unknown';
                  else if ($cls=='license' || $cls=='license-highlite' || $cls=='custom') $c+= 1;
                  
                  if ($cls) $lnk= "<span class='$cls-tag'>$lnk</span>";
              }
              else $c+= 1;
              
              $html.= $lnk;
      }
      
      #if ($html) $html= 'Templates: '.$html;
      
      if (!$c) {
        if ($html) $html.= ', ';
	if (!$templates) $html.= '<span class="untagged">untagged!</span>';
        else $html.= '<span class="untagged">no license tag!</span>';
      }
      
      return $html;
}

function initImageInfo(&$row) {
  global $wq;
  
  if (!isset($row['_text'])) {
      $inf= $wq->wiki->loadInfo($row["img_name"], NS_IMAGE);
      
      if ($inf) {
          $row['_text']= $inf['text'];
          $row['_page_id']= $inf['id'];
      }
      else {
          $row['_text']= NULL;
          $row['_page_id']= NULL;
      }
  }
}

function getGalleries($img) {
  global $wq;

  $sql= 'SELECT page_title
         FROM page
         JOIN imagelinks ON il_from = page_id
         WHERE il_to = '.$wq->wiki->wikiDB->addQuotes($img).'
         AND page_namespace = 0';
         
  $res= $wq->wiki->wikiDB->query($sql,'getGalleries');
  
  $gals= array();
  while ($row = $wq->wiki->wikiDB->fetchRow($res)) {
      $gals[]= $row['page_title'];
  }
  
  $wq->wiki->wikiDB->freeResult($res);
  
  return $gals;
}

function extractCategories($text) {
      global $wq;
      
      $links= $wq->wiki->extractLinks($text);
      $categories= array();
      
      foreach ($links as $e) {
          if (!$e['escaped'] && $wq->wiki->getNsIndex($e['namespace']) === NS_CATEGORY) {
              $categories[]= $e['link'];
          }
      }
      
      return $categories;
}

function getUsageInfo($field, $row) {
  global $wq;

  initImageInfo($row);
  
  $gals= getGalleries($row['img_name']);
  $cats= extractCategories($row['_text']);
  
  $html= '';
  if ($gals) {
      $html.= 'Articles: ';
      
      $first= true;
      foreach ($gals as $t) {
          if ($first) $first= false;
          else $html.= ', ';
          
          $html.= $wq->makeLink($t,NS_MAIN,true);
      }
  }
  
  if ($gals && $cats) $html.= '<br/>';
  
  if ($cats) {
      $html.= 'Categories: ';
      
      $first= true;
      foreach ($cats as $t) {
          if ($first) $first= false;
          else $html.= ', ';
          
          $html.= $wq->makeLink($t,NS_CATEGORY,false);
      }
  }
  
  if (!$gals && !$cats) {
      $html.= '<span class="orphan">orphan!</span>';
      
      $u= "CommonSense.php?i=".urlencode($row['img_name'])."&go-clean=yes";
      $html.= "<br/><small><i><a href='$u'>categorize with CommonSense</a></i></small>";
  }
  
  $u= "CheckUsage.php?i=".urlencode($row["img_name"])."&amp;w=_1000000";
  $html.= "<br/><small><i><a href='$u'>usage in all projects</a></i></small>";
  
  return $html;
}

$sql=  'SELECT image.* FROM image';

$wq= new WikiQuery('Gallery', $sql);
#$wq->setWikiDomain('commons.wikimedia.org');

$wq->chunks= array( 25, 50, 100, 250 );

if (!$wgRequest->getVal('order')) $wq->order= '-img_timestamp';

#img_name as title, img_user, img_user_text, img_timestamp as value, img_description

$wq->fields['img_timestamp']= array(
  'label' => 'Date',
  'html' => true,
  'pattern' => 'return $this->makeDate($row["img_timestamp"]);',
  'sort' => true,
  'hidden' => true,
  'timestamp' => true,
);

$wq->fields['img_user_text']= array(
  'label' => 'User',
  #'html' => true,
  #'function' => 'getUserInfo',
  'sort' => true,
  'filter' => true,
  'filter-normalize' => 'title',
  'hidden' => true,
);

$wq->fields['img_name']= array(
  'label' => 'Name',
  #'html' => true,
  #'function' => 'getFileInfo',
  'filter-normalize' => 'title',
  'sort' => true,
  'hidden' => true,
);

#..........

$wq->fields['thumb']= array(
  'label' => 'Thumb',
  'html' => true,
  'function' => 'getThumbInfo',
  'attributes' => 'style="text-align:center;"',
);

$wq->fields['upload']= array(
  'label' => 'Upload',
  'html' => true,
  'function' => 'getUploadInfo',
);

$wq->fields['tags']= array(
  'label' => 'Tags',
  'html' => true,
  'function' => 'getTagInfo',
);

$wq->fields['usage']= array(
  'label' => 'Usage',
  'html' => true,
  'function' => 'getUsageInfo',
);

#..............

$wq->feedFields= array(
    'date' => 'feed_date',
    'title' => 'img_name',
    'author' => 'img_user_text',
    'url' => 'feed_url',
    'description' => 'feed_info',
);

$wq->fields['feed_url']= array(
  'label' => 'URL',
  'pattern' => 'return $this->makeURL($row["img_name"],NS_IMAGE);',
  'hidden' => true,
);

$wq->fields['feed_date']= array(
  'label' => 'Date',
  'pattern' => 'return $row["img_timestamp"];',
  'hidden' => true,
);

$wq->fields['feed_info']= array(
  'label' => 'Info',
  'html' => true,
  'pattern' => 'initImageInfo($row); return getThumbInfo($field,$row)."<hr/>".getUploadInfo($field,$row)."<hr/>".getTagInfo($field,$row)."<hr/>".getUsageInfo($field,$row)."<hr/><pre>".$row["_text"]."</pre><hr/>";',
  'hidden' => true,
);

$wq->styles[]= '.untagged { color:yellow; background-color:#DD0000; font-weight:bold; font-size:88%; white-space:nowrap; padding-left:1ex; padding-right:1ex; }';
$wq->styles[]= '.orphan { color:yellow; background-color:#DD0000; font-weight:bold; font-size:88%; white-space:nowrap; padding-left:1ex; padding-right:1ex; }';

$wq->styles[]= 'table.query-result { cell-spacing:1ex; }';
$wq->styles[]= 'table.query-result th { background-color:#D0D0D0; padding:1pt 2pt 2pt 2pt; }';
$wq->styles[]= 'table.query-result td { background-color:#F4F4F4; padding:0.5ex; }';
$wq->styles[]= 'table.query-result td img { background-color:#E0E0E0; padding:0.5ex; margin:0; border:1px solid #AAAAAA; }';

$wq->styles[]= '.license-tag { background-color:#DDFFDD; }';
$wq->styles[]= '.license-highlite-tag { background-color:#FFEEAA; }';
$wq->styles[]= '.custom-tag { background-color:#EEFFEE; }';
$wq->styles[]= '.delete-tag { background-color:#FFAAAA; }';
$wq->styles[]= '.problem-tag { background-color:#FFEEAA; }';
$wq->styles[]= '.meta-tag { background-color:#DDDDFF; }';
$wq->styles[]= '.magic-tag { background-color:#DDDDDD; }';
$wq->styles[]= '.unknown-tag { background-color:#FFDDFF; }';

$wq->helpPageName= 'Tools';
$wq->printPage();
?>