Location: PHPKode > projects > Scriptorium > scriptorium1.6/add_script.php
<?php

require('includes/scriptorium_inc.php');

if (!isset($_SESSION['auth']['isLoggedIn'])) {
  header("Location: index.php");
}


function chooseEnvironment() {
  global $db;
  $f = new HTML_Form($_SERVER['SCRIPT_NAME'],"post","addForm");

  $environments = getEnvironments();
  
  if (sizeof($environments) > 0) {
    $field = $f->returnSelect("eid",$environments,"",1,"--"
			      .lib('listbox_select')."--");
    $submit = $f->returnSubmit(lib('submit'));
    
    $output = $f->returnStart(true)
      .'<h2>'.lib('env_selection').'</h2><p>'.lib('which_env').'</p>'
      .$field.'<p>'.$submit.'</p>';
    $output .= $f->returnEnd();
  } else {
    $output = lib('no_environments');
  }
  
  return $output;
}
  
function displayAddForm($eid) {
  global $db, $LOCALES; 

  $f = new HTML_Form($_SERVER['SCRIPT_NAME'],"post","addForm");
  $t = new HTML_Table('border="0" cellpadding="7" cellspacing="0"');

  $eid = (int)$_REQUEST['eid'];
  $cid = (int)$_REQUEST['cid'];

  $t->addRow(array("<h2>".lib('adding_script_to').': ' . eidToName($eid) . " </h2>"));
  
  // Text Language 
  $field = '';
  foreach ($LOCALES as $lc) {
  	if ($_SESSION['locale'] == $lc) {
		$lcDef = 'on';
	} else {
		$lcDef = 'off';
	}
  	$field .= $f->returnRadio('script_locale', $lc, $lcDef);
	$field .= "<img src='images/locale_$lc.png' alt='$lc'>";
  }
  $t->addRow(array('&nbsp;',$field));

  // name 
  $field = $f->returnText("name","","","textbox");
  $t->addRow(array('<b>'.lib('name').':</b>',$field));

  // attribution
  $field = $f->returnText("attribution","","","textbox");
  $t->addRow(array('<b>'.lib('attribution').':</b>',$field));
  
  // owner
  if ($_SESSION['auth']['level'] >= 100) {
  	  $getUsers = getUsers();
	  $users = array();
	  foreach ($getUsers as $user) {
	  	$users[$user->user_id] = $user->username;
	  }
	  $field = $f->returnSelect("user_id",
				$users, $_SESSION['auth']['userId'], 1);
	  $t->addRow(array('<b>'.lib('added_by').':</b>',$field));
  }

  // categories menu
  $field = $f->returnSelect("category_id",
  			getCategories($eid), $cid, 1, lib("no_category"));
  if ($_SESSION['auth']['level'] >= 100) {
	  $field .= "<p>".lib('new_category').":</p>";
	  $field .= $f->returnText("new_category_name","","","textbox");
  }
  $t->addRow(array('<b>'.lib('category').':</b>',$field));

  // types menu
  $field = $f->returnSelect("type_id",
  			getTypes(),"",1,"--".lib('listbox_select')."--");
  $t->addRow(array('<b>'.lib('type').':</b>',$field));

  // language menu
  $sql = "SELECT id_language, force_language FROM scriptorium_environments"
		." WHERE id=$eid";
  $env = $db->getRow($sql,DB_FETCHMODE_OBJECT);
  if ($env->force_language != 1) {
	  $field = $f->returnSelect("language_id",
				getLanguages(),$env->id_language,1,
				"--".lib('listbox_select')."--");
	  $t->addRow(array('<b>'.lib('language').':</b>',$field));
  }
  
  // description
  $field = $f->returnTextarea("description", '', '', 3);
  if (USE_SPELLCHECK) {
	$field .= addSpellcheckLink('document.addForm.description');
  }
  $field .= addRewrapLink('document.addForm.description');
  $t->addRow(array('<b>'.lib('description').':</b>', $field));

  // notes
  $field = $f->returnTextArea("note");
  if (USE_SPELLCHECK) {
	$field .= addSpellcheckLink('document.addForm.note');
  }
  $field .= addRewrapLink('document.addForm.note');
  $t->addRow(array("<b>".lib('notes').":</b>",$field));

  // sample usage
  $field = $f->returnTextArea("sample_usage");
  $t->addRow(array('<b>'.lib('usage').':</b>', $field));

  // code
  $field = $f->returnTextArea("code","","",30 );
  $t->addRow(array("<b>".lib('code').":</b>",$field));

  // file upload
  $max_upload_size = ini_get('upload_max_filesize');
  $field = $f->returnFile("file");
  $field .= "<br /><i>".lib('max_upload_size', $max_upload_size)."</i>";
  $t->addRow(array('<b>'.lib('file').':</b>',$field));

  // related urls
  $field = $f->returnTextArea("urls");
  $t->addRow(array("<b>".lib('related_urls').":</b>",$field));
 
  // dependencies
  $environment_scripts = getAllScripts($eid, 0, true);
  
  if (count($environment_scripts) > 0) {
    $dependency_group = "<div id='dependencyGroup'>\n";
    foreach ($environment_scripts as $script) {
      $field = $f->returnCheckbox("dependencies[]", $script->id);
      $script->name = stripslashes($script->name);
	  $category_name = trim(stripSlashes($_SESSION['scriptorium_categories'][$script->category_id]));
	  if ($last_category != $category_name) {
		$dependency_group .= "<br><b><u>$category_name</u></b><br>";
		$last_category = $category_name;
	  }
      $dependency_group .= "{$field}&nbsp;<a target='new' href='view.php?sid={$script->id}'>{$script->name}</a><br />\n";
    }
    $dependency_group .= "</div>&nbsp;\n";

    $t->addRow(array("<a id='dependencyLink' href='#' onclick=\"toggleDependencies(); return false\"><b>".lib('dependencies').":</b></a>",$dependency_group));
  }
  
  // submit
  $t->addRow(array("&nbsp;",$f->returnSubmit(lib('submit'))),'align="center"');

  $t->updateColAttributes(0,'valign="top" width="100" align="right"');
  $t->updateColAttributes(1,'valign="top" width="100%" ');
  $t->setRowAttributes(0,'colspan="2"');


  $f->onsubmit = "return checkAddScript(this)";
  $output = $f->returnStart(true);
  $output .= $f->returnHidden('action','add');
  $output .= $f->returnHidden('sid',$_REQUEST['sid']);
  $output .= $t->toHTML();
  $output .= $f->returnHidden('eid',$_REQUEST['eid']);
  if ($env->force_language) {
  	$output .= $f->returnHidden('language_id',$env->id_language);
  }
  $output .= $f->returnEnd();
  
  return($output); 
}

function commitAdd() {
  global $db;

  $script_locale = $db->quote($_POST['script_locale']);
  $name = $db->quote($_POST['name']);

  if (trim($_POST['attribution']) != "") {
    $attribution_sql = ", attribution='" . addslashes(trim($_POST['attribution'])) . "'";
  } else {
    $attribution_sql = "";
  }
  $eid = $_POST['eid'];

  $new_category = trim($_POST['new_category_name']);
  $new_category = stripslashes($new_category);

  if ($new_category == "") {
    $category_id = $_POST['category_id'];
    if ($category_id == "") {
      $category_id = 0;
    }
  } else {
    $category_id = $db->nextID('scriptorium_categories');
    $sql_insert_category = <<<SQL
    
INSERT INTO scriptorium_categories (environment_id,name)
VALUES ($eid,'$new_category')

SQL;

    $result = $db->query($sql_insert_category);

    if ($db->isError($result)) {
      $message = "Unable to add new category. <a href='add_script.php?eid=$eid'>Click here</a> to try again.";
      return displayError($message);
    }

  }
  $destination_folder = FILE_UPLOAD_PATH . '/';
  $destination_folder .= makeFilesystemName(eidToName($_POST['eid'], true)) . '/';
  $destination_folder .= makeFilesystemName(cidToName($category_id, true)) . '/';

  if (isset($_POST['access_level'])) {
    $access_level = (int)$_POST['access_level'];
  } else {
    $access_level = 0;
  }

  $description = $_POST['description'];
  $description = str_replace('\\','\\\\',$description);
  $description = $db->quote($description);

  $sample_usage = $_POST['sample_usage'];
  $sample_usage = str_replace('\\','\\\\',$sample_usage);
  $sample_usage = $db->quote($sample_usage);

  $code = $_POST['code'];
  $code = str_replace('\\','\\\\',$code);
  $code = $db->quote($code);


  if (TAB_TO_SPACE_CONVERSION > 0) {
    $code = str_replace("\t",str_repeat(' ',TAB_TO_SPACE_CONVERSION),$code);
  }

  if (isset($_POST['file'])) {
    $file = $db->quote($_POST['file']);
  } else {
    $file = '';
  }

  $urls = explode("\r\n",trim($_POST['urls']));

  $note = $_POST['note'];
  $note = str_replace('\\','\\\\',$note);
  $note = $db->quote($note);

  $type_id = $_POST['type_id'];
  if ($type_id == "") {
    $type_id = 0;
  }
  if (!$_POST['user_id']) {
	  $author_id = $_SESSION['auth']['userId'];
  } else {
	  $author_id = $_POST['user_id'];
  }

  if (isset($_POST['dependencies'])) {
    $dependencies = $_POST['dependencies'];
  } else {
    $dependencies = array();
  }

  $commitError = false;
  if (is_uploaded_file($_FILES['file']['tmp_name'])) {
    if (file_exists($destination_folder . $_FILES['file']['name'])) {
      $commitError = true;
      $t = new HTML_Table('class="normalBackground"  border="0" cellpadding="10" cellspacing="0"');
      $t->addRow(array("<h2>".lib('warning')."</h2>"));
      $t->addRow(array("&nbsp;", lib('file_already_exists') ));
      $t->setColAttributes(0,'class="colBackground" valign="top" width="10"');
      $t->setRowAttributes(0,'class="rowBackground" colspan="2"');
    } else {
      mkdir_recursive($destination_folder);
      $destination_path = $destination_folder . '/' . $_FILES['file']['name'];

      if(move_uploaded_file($_FILES['file']['tmp_name'],$destination_path)) {
        chmod($destination_path,DEFAULT_PERMISSIONS);
      } else {
        return displayError(lib('err_upload_file'));
      }
      $file_file = $_FILES['file']['name'];
      $file_sql = ", file = " . $db->quote($file_file);
    }
  } elseif ($_FILES['file']['name'] != '' && $_FILES['file']['size'] == 0) {
    return displayError(lib('err_file_size'));
  } else {
    $file_sql = "";
  }

  $language_id = (int)$_POST['language_id'];

  $sql_update_script = <<<SQL
      
INSERT INTO scriptorium_scripts 
SET name=$name,
    environment_id=$eid,
    category_id=$category_id,
    description=$description,
    sample_usage=$sample_usage,
    code=$code,
    note=$note,
    date_added=NOW(),
    date_modified=NOW(),
    type_id=$type_id,
    fk_access_level=$access_level,
    author_id=$author_id,
	script_locale=$script_locale,
    fk_language_id=$language_id
    $attribution_sql
    $file_sql
SQL;

  $result = $db->query($sql_update_script);
  $try_again = "<a href='add_script.php?eid=$eid'>"
				.lib('unable_try_again')."</a>";

  if ($db->isError($result)) {
    return displayError(lib('unable_to_add_script').$try_again);
  }

  // increment the scripts sequence
  $inserted_id = $db->nextId('scriptorium_scripts');

  // urls
  if ($urls[0] != "") {
    foreach ($urls as $url) {
      $url = addslashes($url);
      $sql = "INSERT INTO scriptorium_urls (script_id,address) VALUES ($inserted_id,'$url')";
      $db->query($sql);
    }    

    if ($db->isError($result)) {
      return displayError(lib('unable_to_add_urls').$try_again);
    }
  }

  // dependencies
  $dependencies_sql = '';
  if (sizeof($_POST['dependencies']) > 0) {
    $sid = $inserted_id;

    foreach ($dependencies as $dependency) {
      $dependencies_sql .= "($sid,$dependency),";
    }

    $dependencies_sql = rtrim($dependencies_sql,",");
    $sql_insert_dependencies = "INSERT INTO scriptorium_dependencies (source,target) VALUES $dependencies_sql";
 
    $result = $db->query($sql_insert_dependencies);
    if ($db->isError($result)) {
      $message = lib('unable_to_add_deps')."<a href='edit_script.php?eid={$_GET['eid']}&cid=$category_id&sid={$_POST['sid']}'>".lib('unable_try_again')."</a>";
      return displayError($message);
    }  
  }
  
  if ($commitError) {
    return $t->toHTML();
  } else {
    // this is called after every filesystem-related change 
    // as a housekeeping measure, even if its unnecessary
    moveFilesOutOfRoot();


    // send notifications
    sendEmailNotifications($eid,$category_id,$name,$inserted_id,$author_id);
    
    header("Location: view.php?eid=$eid&sid=$inserted_id");
    exit();
  }
}

if (isset($_POST['action']) && $_POST['action'] == 'add') {
  $content = commitAdd();
  $smarty->assign('content',$content);  
} else {
  if ($_GET['sid']) {
	$_REQUEST['eid'] = $db->getOne("SELECT environment_id FROM scriptorium_scripts WHERE id=".$db->quote($_GET['sid']));
  }
  if (!isset($_REQUEST['eid']) || $_REQUEST['eid'] == '') {
    $content = chooseEnvironment();
    $smarty->assign('content',$content);
    $smarty->assign('page_title', lib('title_add_script_env'));
  } else {
    $content = displayAddForm($_REQUEST['eid']);
    $smarty->assign('content',$content);
    $smarty->assign('page_title', lib('title_add_script'));
  }
}

$smarty->display('main.tpl.html')


?>
Return current item: Scriptorium