<?php
if (!$_SESSION["OBJ_user"]->isDeity())
{
  header("location:index.php");
  exit();
}

$status = 1;
$now = date("Y-m-d H:i:s");

if($currentVersion < 1.3) 
{
  $content .= 'Updating Article Manager to version 1.3<br />';
  $content .= 'Adding column "brand_printable" to "mod_article_config".<br />';
  $sql = 'ALTER TABLE ' . PHPWS_TBL_PREFIX 
    . 'mod_article_config ADD `brand_printable` smallint NOT NULL DEFAULT "0" AFTER `make_metatags`';
  $result = $GLOBALS['core']->query($sql);
  if(DB::isError($result)) 
  {
    $content .= 'There was an error when attempting to alter the mod_article_config table:<br />'
      . $result->getMessage() . '<br />';
    $status = 0;
  } 
  else 
  {
    $content .= 'Column added successfully!';
  }
}
if($currentVersion < 1.4) 
{
  $content .= 'Updating Article Manager to version 1.4<br />'
    . 'Converting Spaces to Underscores in all template names.<br />';
	/* Retrieve all articles to update */
  $sql = 'SELECT id,template FROM mod_article';
  if(!$result = $GLOBALS['core']->query($sql, true)) 
    $content .= '<br />'.$_SESSION['translate']->it('ERROR: No [var1] were found!','articles').'<br />';
  else
    while($row=$result->fetchrow(DB_FETCHMODE_ASSOC)) 
      $GLOBALS['core']->query('UPDATE mod_article SET template="'.str_replace(' ','_',$row['template'])
        . '" WHERE id='.$row['id'], true);
  $row = array();
  $result = null;
	/* Retrieve all sections to update */
  $sql = 'SELECT id,template FROM mod_article_sections';
  if(!$result = $GLOBALS['core']->query($sql, true)) 
    $content .= '<br />'.$_SESSION['translate']->it('ERROR: No [var1] were found!','sections').'<br />';
  else
    while($row=$result->fetchrow(DB_FETCHMODE_ASSOC)) 
      $GLOBALS['core']->query('UPDATE mod_article_sections SET template="'.str_replace(' ','_',$row['template'])
        . '" WHERE id='.$row['id'], true);
  $row = array();
  $result = null;
	/* Retrieve configuration row for updating */
  $sql = 'SELECT default_article_template,default_section_template FROM mod_article_config';
  if(!$result = $GLOBALS['core']->query($sql, true)) 
    $content .= '<br />'.$_SESSION['translate']->it('ERROR: No [var1] were found!','configuration datum').'<br />';
  else
    while($row=$result->fetchrow(DB_FETCHMODE_ASSOC)) 
      $GLOBALS['core']->query('UPDATE mod_article_config SET '
        . 'default_article_template="'.str_replace(' ','_',$row['default_article_template'])
        . '",default_section_template="'.str_replace(' ','_',$row['default_section_template'])
        . '"', true);
  $row = array();
  $result = null;

  /* Delete the old template files */
  if ( ! function_exists('delfile') ) 
  {
    function delfile ($dir, $file)
    {
      if (file_exists(PHPWS_SOURCE_DIR . $dir . $file))
      {
        if (unlink(PHPWS_SOURCE_DIR . $dir . $file))
          return $file.' Deleted.<br />';
        else
          return 'ERROR: '.$file.' could not be deleted.  Please delete it manually.<br />';
      }
    }
    $content .= 'Deleting old template files (the ones with spaces in the names)<br />';
    $content .= delfile('mod/article/templates/section/','Centered Image.tpl');
    $content .= delfile('mod/article/templates/section/','Image Block Left.tpl');
    $content .= delfile('mod/article/templates/section/','Image Block Right.tpl');
    $content .= delfile('mod/article/templates/section/','Image Wrap Left.tpl');
    $content .= delfile('mod/article/templates/section/','Image Wrap Right.tpl');
    $content .= delfile('mod/article/templates/section/','No Images.tpl');
    $content .= delfile('mod/article/templates/section/','Text Only.tpl');
    $content .= delfile('mod/article/templates/section/','Page Insertion (Fit Block).tpl');
    $content .= delfile('mod/article/templates/section/','Page Insertion (Fit Page).tpl');
    $content .= delfile('mod/article/templates/section/','Page Insertion (Max Page).tpl');
    $content .= delfile('mod/article/templates/section/','Page Insertion (Title is Size).tpl');
  }

  /* Rename template files inside themes */
  if ( ! function_exists('renameThemeFile') ) 
  {
    function renameThemeFile ($theme, $file)
    {
      $oldname = "themes/$theme/templates/article/section/".$file;
      $newname = "themes/$theme/templates/article/section/".str_replace(' ','_',$file);
    	if (!file_exists($GLOBALS['core']->home_dir . $oldname))
    	  return;
      if (rename($GLOBALS['core']->home_dir.$oldname, $GLOBALS['core']->home_dir.$newname))
        return $file.' was Renamed.<br />';
      else
        return 'ERROR: '.$oldname.' could not be renamed.  Please rename it as '
              .$newname.' manually.<br />';
    }
  }

  $theme_names = $_SESSION['OBJ_layout']->get_themes();
  $content .= 'Renaming old template files in themes<br />';
  foreach($theme_names AS $theme)
  {
    $content .= 'Checking theme '.$theme.'<br />';
    $content .= renameThemeFile($theme,'Centered Image.tpl');
    $content .= renameThemeFile($theme,'Image Block Left.tpl');
    $content .= renameThemeFile($theme,'Image Block Right.tpl');
    $content .= renameThemeFile($theme,'Image Wrap Left.tpl');
    $content .= renameThemeFile($theme,'Image Wrap Right.tpl');
    $content .= renameThemeFile($theme,'No Images.tpl');
    $content .= renameThemeFile($theme,'Text Only.tpl');
    $content .= renameThemeFile($theme,'Page Insertion (Fit Block).tpl');
    $content .= renameThemeFile($theme,'Page Insertion (Fit Page).tpl');
    $content .= renameThemeFile($theme,'Page Insertion (Max Page).tpl');
    $content .= renameThemeFile($theme,'Page Insertion (Title is Size).tpl');
  }
  $content .= 'Update to 1.4 Finished!<br />';
}
if (!function_exists('delfile') ) 
{
  function delfile ($dir, $file)
  {
    if (file_exists(PHPWS_SOURCE_DIR . $dir . $file))
    {
      if (unlink(PHPWS_SOURCE_DIR . $dir . $file))
        return $file.' Deleted.<br />';
      else
        return 'ERROR: '.$file.' could not be deleted.  Please delete it manually.<br />';
    }
  }
}
if($currentVersion < 1.5) 
{
  $content .= 'Updating Article Manager to version 1.5<br />';
  $content .= 'Fixing publication dates on all articles that have already been published...';
  $sql = 'UPDATE ' . PHPWS_TBL_PREFIX 
    . 'mod_article SET publication_date=created_date WHERE publication_date<"'.$now.'"';
  if ($GLOBALS['core']->query($sql))
    $content .= 'Done!<br />';
  else
    $content .= 'Update Failed!<br />Try to run this sql command on your database manually: '.$sql.'<br />';

  $content .= '<br />Deleting old template files (the ones with spaces in the names)<br />'
      . delfile('mod/article/templates/section/','.#Centered Image.removed.tpl')
      . delfile('mod/article/templates/section/','.#Image Block Left.removed.tpl')
      . delfile('mod/article/templates/section/','.#Image Block Right.removed.tpl')
      . delfile('mod/article/templates/section/','.#Image Wrap Left.removed.tpl')
      . delfile('mod/article/templates/section/','.#Image Wrap Right.removed.tpl')
      . delfile('mod/article/templates/section/','.#No Images.removed.tpl')
      . delfile('mod/article/templates/section/','.#Text Only.removed.tpl')
      . delfile('mod/article/templates/section/','.#Page Insertion (Fit Block).removed.tpl')
      . delfile('mod/article/templates/section/','.#Page Insertion (Fit Page).removed.tpl')
      . delfile('mod/article/templates/section/','.#Page Insertion (Max Page).removed.tpl')
      . delfile('mod/article/templates/section/','.#Page Insertion (Title is Size).removed.tpl');
  $content .= 'Update to 1.5 Finished!<br />';
}
if($currentVersion < '2.0') 
{
  $content .= 'Updating Article Manager to version 2.0<br />';
  $content .= 'Adding columns "meta_keywords" and "meta_robots" to table mod_article.<br />';
  $sql = 'ALTER TABLE ' . PHPWS_TBL_PREFIX 
    . 'mod_article ADD (meta_keywords varchar(100) NOT NULL DEFAULT "", meta_robots char(2) NOT NULL DEFAULT "")';
  if ($GLOBALS['core']->query($sql))
    $content .= 'Columns added successfully!<br />';
  else
    $content .= 'Update Failed!<br />Try to run this sql command on your database manually: '.$sql.'<br />';
  $_SESSION['OBJ_help']->uninstall_help('article');
  $_SESSION['OBJ_help']->setup_help('article');
  $content .= 'Update to 2.0 Finished!<br />';
}
if($currentVersion < '2.2') 
{
  $content .= 'Updating Article Manager to version 2.2<br />';
  $content .= 'Adding column "created_id" to table mod_article...';
  $sql = 'ALTER TABLE mod_article ADD created_id int NOT NULL DEFAULT 0 AFTER created_username';
  if ($GLOBALS['core']->query($sql, true))
    $content .= 'Column added successfully!<br />';
  else
    $content .= 'Update Failed!<br />Try to run this sql command on your database manually: '.$sql.'<br />';

  $content .= 'Adding column "use_comments" to table mod_article_config...';
  $sql = 'ALTER TABLE mod_article_config ADD (use_comments smallint NOT NULL DEFAULT 1)';
  if ($GLOBALS['core']->query($sql, true))
    $content .= 'Column added successfully!<br />';
  else
    $content .= 'Update Failed!<br />Try to run this sql command on your database manually: '.$sql.'<br />';
  $content .= 'Update to 2.2 Finished!<br />';
}

if($currentVersion < 2.3) 
{
  $content .= 'Updating Article Manager to version 2.3<br />'
    . 'Fixing Year Display Minimums.<br />';
  $sql = 'UPDATE mod_article_config SET default_year_count=1 WHERE default_year_count=0';
  $result = $GLOBALS['core']->query($sql, true);
  if(DB::isError($result)) {
    $content .= 'There was an error while attempting to update the mod_article_config table:<br />'
      . $result->getMessage() . '<br />';
    $status = 0;
  } 
  else {
    $content .= 'Update to 2.3 Finished!<br />';
  }
}
if($currentVersion < '2.5') 
{
  $prefix = $GLOBALS['core']->getTablePrefix();
  $content .= 'Updating Article Manager to version 2.5<br />'
    . 'Finalizing Version Control System.<br />'
    . '     Adding archive columns...';
  if($GLOBALS['core']->sqlTableExists('mod_article_oldversions',1))
    $GLOBALS['core']->sqlDropTable('mod_article_oldversions');
  $columns = array();
  $columns['id']                = 'int PRIMARY KEY';
  $columns['article_id']        = 'int NOT NULL';
  $columns['version']           = 'int NOT NULL';
  $columns['archived_date']     = 'datetime NOT NULL';
  $columns['updated_userid']    = 'int NOT NULL DEFAULT "0"';
  $columns['numadded']          = 'smallint NOT NULL DEFAULT "0"';
  $columns['numdeleted']        = 'smallint NOT NULL DEFAULT "0"';
  $columns['numchanged']        = 'smallint NOT NULL DEFAULT "0"';
  $columns['article']           = 'text NOT NULL';
  $GLOBALS['core']->sqlCreateTable('mod_article_oldversions', $columns);
  $content .= 'Done<br />';
  $content .= 'Creating new indexes...';
  $GLOBALS['core']->sqlCreateIndex('mod_article_oldversions', array('article_id'));
  $GLOBALS['core']->sqlCreateIndex('mod_article_oldversions', array('version'));
  $content .= 'Done<br />';
  $content .= 'Adding new configuration settings...';
  if(!$GLOBALS['core']->sqlColumnExists('mod_article_config', 'archive_days'))
    $GLOBALS['core']->sqlAddColumn('mod_article_config', array('archive_days'=>'smallint NOT NULL DEFAULT "7"'));
  $content .= 'Done<br />';

  $content .= 'Placing user ids of article authors...';
  /* Make a list of names and userids of all article creators */
  $sql = 'SELECT a.created_username, u.user_id FROM '.$prefix.'mod_article AS a LEFT JOIN '.$prefix.'mod_users AS u ON ( u.username = a.created_username ) WHERE NOT (a.created_username = "") GROUP BY a.created_username';
  $result = $GLOBALS['core']->query($sql);
  while ($result && $row = $result->fetchrow(DB_FETCHMODE_ASSOC)) {
    if(!$row['user_id'])
      $row['user_id'] = '0';
    $GLOBALS['core']->query('UPDATE mod_article SET created_id='.$row['user_id'].' WHERE created_username ="'.$row['created_username'].'"', true);
  }
  $content .= 'Done!<br />';

  $content .= 'Adding column "updated_id" to table mod_article...';
  $sql = 'ALTER TABLE mod_article ADD updated_id int NOT NULL DEFAULT 0 AFTER updated_username';
  if ($GLOBALS['core']->query($sql, true))
    $content .= 'Column added successfully!<br />';
  else
    $content .= 'Update Failed!<br />Try to run this sql command on your database manually: '.$sql.'<br />';

  $content .= 'Placing user ids of article editors...';
  /* Make a list of names and userids of all article editors */
  $sql = 'SELECT a.updated_username, u.user_id FROM '.$prefix.'mod_article AS a LEFT JOIN '.$prefix.'mod_users AS u ON ( u.username = a.updated_username ) WHERE NOT (a.updated_username = "") GROUP BY a.updated_username';
  $result = $GLOBALS['core']->query($sql);
  while ($result && $row = $result->fetchrow(DB_FETCHMODE_ASSOC)) {
    if(!$row['user_id'])
      $row['user_id'] = '0';
    $GLOBALS['core']->query('UPDATE mod_article SET updated_id='.$row['user_id'].' WHERE updated_username ="'.$row['updated_username'].'"', true);
  }
  $content .= 'Done!<br />';

	/* Update page & section template spellings */
  $content .= 'Updating section template names.<br />';
  $GLOBALS['core']->query('UPDATE mod_article_sections SET template="Page_Insertion_to_Fit_Block.tpl" WHERE template="Page_Insertion_(Fit_Block).tpl"', true);
  $GLOBALS['core']->query('UPDATE mod_article_sections SET template="Page_Insertion_to_Fit_Page.tpl" WHERE template="Page_Insertion_(Fit_Page).tpl"', true);
  $GLOBALS['core']->query('UPDATE mod_article_sections SET template="Page_Insertion_for_Max_Page.tpl" WHERE template="Page_Insertion_(Max_Page).tpl"', true);
  $GLOBALS['core']->query('UPDATE mod_article_sections SET template="Page_Insertion_with_Title_is_Size.tpl" WHERE template="Page_Insertion_(Title_is_Size).tpl"', true);

  /* Delete the old template files */
  if ( ! function_exists('delfile') ) 
  {
    function delfile ($dir, $file)
    {
      if (file_exists(PHPWS_SOURCE_DIR . $dir . $file))
      {
        if (unlink(PHPWS_SOURCE_DIR . $dir . $file))
          return $file.' Deleted.<br />';
        else
          return 'ERROR: '.$file.' could not be deleted.  Please delete it manually.<br />';
      }
    }
    $content .= 'Deleting old template files (the ones with parentheses in the names)<br />';
    $content .= delfile('mod/article/templates/section/','Page_Insertion_(Fit_Block).tpl');
    $content .= delfile('mod/article/templates/section/','Page_Insertion_(Fit_Page).tpl');
    $content .= delfile('mod/article/templates/section/','Page_Insertion_(Max_Page).tpl');
    $content .= delfile('mod/article/templates/section/','Page_Insertion_(Title_is_Size).tpl');
  }

  $content .= 'Re-registering with the Search Module....Done.<br />';
  require_once(PHPWS_SOURCE_DIR.'mod/search/class/Search.php');
  PHPWS_Search::register('article');
  $content .= 'Update Complete!';
}

if(false) //($currentVersion < '3.0') 
{
  $prefix = $GLOBALS['core']->getTablePrefix();
  $content .= 'Updating Article Manager to version 3.0<br />';

  if(!$GLOBALS['core']->sqlColumnExists('mod_article', 'language')) {
    $content .= 'Adding new language columns to table mod_article...';
    $GLOBALS['core']->sqlAddColumn('mod_article', array('language'=>'char(2) NOT NULL DEFAULT ""','translation_group'=>'int NOT NULL'));
    $content .= 'Creating new indexes...';
    $GLOBALS['core']->sqlCreateIndex('mod_article', array('language','translation_group'));
    $content .= 'Done<br />';
  }
  else
    $content .= 'Language columns already in place<br />';

  if(!empty($_SESSION['translate']->default_language)) {
    $content .= 'Setting all articles to current language...';
    if($GLOBALS['core']->query('UPDATE mod_article SET language="'.$_SESSION['translate']->default_language.'"', true))
      $content .= 'Done<br />';
    else
      $content .= 'Operation Failed.<br />';
  }
  $content .= 'Setting all translation group ids...';
  if($GLOBALS['core']->query('UPDATE mod_article SET translation_group=id', true))
    $content .= 'Done<br />';
  else
    $content .= 'Operation Failed.<br />';

  $content .= 'Update Complete!';
}
?>