/**
  * This function will process uploaded file
  *
  * @param array $uploaded_file
  * @param boolean $create_revision Create new revision or update last one
  * @param string $revision_comment Revision comment, if any
  * @return ProjectFileRevision
  */
 function handleUploadedFile($uploaded_file, $create_revision = true, $revision_comment = '')
 {
     $revision = null;
     if (!$create_revision) {
         $revision = $this->getLastRevision();
     }
     // if
     if (!$revision instanceof ProjectFileRevision) {
         $revision = new ProjectFileRevision();
         $revision->setFileId($this->getId());
         $revision->setRevisionNumber($this->getNextRevisionNumber());
         if (trim($revision_comment) == '' && $this->countRevisions() < 1) {
             $revision_comment = lang('initial versions');
         }
         // if
     }
     // if
     $revision->deleteThumb(false);
     // remove thumb
     // We have a file to handle!
     //executes only while uploading files
     if (!is_array($uploaded_file) || !isset($uploaded_file['name']) || !isset($uploaded_file['size']) || !isset($uploaded_file['type']) || (!isset($uploaded_file['tmp_name']) || !is_readable($uploaded_file['tmp_name']))) {
         throw new InvalidUploadError($uploaded_file);
     }
     // if
     if (isset($uploaded_file['error']) && $uploaded_file['error'] > UPLOAD_ERR_OK) {
         throw new InvalidUploadError($uploaded_file);
     }
     // if
     //eyedoc MOD
     $extension = get_file_extension(basename($uploaded_file['name']));
     if ($uploaded_file['type'] == 'application/octet-stream' && $extension == 'eyedoc') {
         $uploaded_file['type'] = 'text/html';
     }
     //eyedoc MOD
     // calculate hash
     if ($revision->columnExists('hash')) {
         $hash = hash_file("sha256", $uploaded_file['tmp_name']);
         $revision->setColumnValue('hash', $hash);
     }
     $repository_id = FileRepository::addFile($uploaded_file['tmp_name'], array('name' => $uploaded_file['name'], 'type' => $uploaded_file['type'], 'size' => $uploaded_file['size']));
     $revision->setRepositoryId($repository_id);
     $revision->deleteThumb(false);
     $revision->setFilesize($uploaded_file['size']);
     if (config_option('detect_mime_type_from_extension')) {
         $type = Mime_Types::instance()->get_type($extension);
         if ($type) {
             $revision->setTypeString($type);
         } else {
             $revision->setTypeString($uploaded_file['type']);
         }
     } else {
         $revision->setTypeString($uploaded_file['type']);
     }
     if (trim($extension)) {
         $file_type = FileTypes::getByExtension($extension);
         if ($file_type instanceof Filetype) {
             $revision->setFileTypeId($file_type->getId());
         }
         // if
     }
     // if
     $revision->setComment($revision_comment);
     $revision->save();
     $this->last_revision = $revision;
     // update last revision
     return $revision;
 }
 private function generatePictureFile($source_file, $max_size, $tmp_filename = "")
 {
     if (!$tmp_filename) {
         $tmp_filename = CACHE_DIR . "/" . gen_id() . ".png";
     }
     if (!is_file($source_file)) {
         return null;
     }
     if (!$max_size) {
         $max_size = 600;
     }
     Env::useLibrary('simplegd');
     $image = new SimpleGdImage($source_file);
     if ($image->getWidth() > $max_size || $image->getHeight() > $max_size) {
         if ($image->getWidth() > $image->getHeight()) {
             $w = $max_size;
             $ratio = $image->getHeight() / $image->getWidth();
             $h = $ratio * $w;
         } else {
             $h = $max_size;
             $ratio = $image->getWidth() / $image->getHeight();
             $w = $ratio * $h;
         }
         $new_image = $image->resize($w, $h, false);
         $new_image->saveAs($tmp_filename);
         $repo_id = FileRepository::addFile($tmp_filename, array('type' => 'image/png', 'public' => true));
         @unlink($tmp_filename);
         return $repo_id;
     } else {
         return null;
     }
 }
	function import_from_vcard() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		@set_time_limit(0);
		ini_set('auto_detect_line_endings', '1');
		if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) unset($_SESSION['go_back']);
		if (isset($_SESSION['go_back'])) {
			unset($_SESSION['go_back']);
			ajx_current("start");
		} else {
                
                    if(!Contact::canAdd(logged_user(), active_context())) {
                            flash_error(lang('no access permissions'));
                            ajx_current("empty");
                            return;
                    } 

                    $this->setTemplate('vcard_import');
                    tpl_assign('import_type', 'contact');                

                    $filedata = array_var($_FILES, 'vcard_file');
                    if (is_array($filedata)) {
                            $filename = ROOT.'/tmp/'.logged_user()->getId().'temp.vcf';
                            copy($filedata['tmp_name'], $filename);
                            $result = $this->read_vcard_file($filename);
                            unlink($filename);
                            $import_result = array('import_ok' => array(), 'import_fail' => array());

                            foreach ($result as $contact_data) {
                                    try {
                                            DB::beginWork();
                                            if (isset($contact_data['photo_tmp_filename'])) {
                                                $file_id = FileRepository::addFile($contact_data['photo_tmp_filename'], array('public' => true));
                                                $contact_data['picture_file'] = $file_id;
                                                unlink($contact_data['photo_tmp_filename']);
                                                unset($contact_data['photo_tmp_filename']);
                                            }
                                            if (isset($contact_data['company_name'])) {
                                                $company = Contacts::findOne(array("conditions" => "`first_name` = '".mysql_real_escape_string($contact_data['company_name'])."'"));
                                                if ($company == null) {                                                        
                                                        $company = new Contact();
                                                        $company->setObjectName($contact_data['company_name']);
                                                        $company->setIsCompany(1);
                                                        $company->save();                                                        
                                                        ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                                                }
                                                $contact_data['company_id'] = $company->getObjectId();
                                                unset($contact_data['company_name']);
                                            }

                                            $contact_data['import_status'] = '('.lang('updated').')';
                                            $fname = DB::escape(array_var($contact_data, "first_name"));
                                            $lname = DB::escape(array_var($contact_data, "surname"));
                                            $email_cond = array_var($contact_data, "email") != '' ? " OR email_address = '".array_var($contact_data, "email")."'" : "";
                                            $contact = Contacts::findOne(array(
                                                "conditions" => "first_name = ".$fname." AND surname = ".$lname." $email_cond",
                                                'join' => array(
                                                        'table' => ContactEmails::instance()->getTableName(),
                                                        'jt_field' => 'contact_id',
                                                        'e_field' => 'object_id',
                                                )));                                                        
                                            $log_action = ApplicationLogs::ACTION_EDIT;
                                            if (!$contact) {
                                                    $contact = new Contact();
                                                    $contact_data['import_status'] = '('.lang('new').')';
                                                    $log_action = ApplicationLogs::ACTION_ADD;
                                                    $can_import = active_project() != null ? $contact->canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user());
                                            } else {
                                                    $can_import = $contact->canEdit(logged_user());
                                            }

                                            if ($can_import) {
                                                    $comp_name = DB::escape(array_var($contact_data, "company_id"));
                                                    if ($comp_name != '') {
                                                            $company = Contacts::findOne(array("conditions" => "first_name = $comp_name AND is_company = 1"));
                                                            if ($company) {
                                                                    $contact_data['company_id'] = $company->getId();
                                                            } 
                                                            $contact_data['import_status'] .= " " . lang("company") . " $comp_name";
                                                    } else {
                                                            $contact_data['company_id'] = 0;
                                                    }
                                                    $contact_data['birthday'] = $contact_data["o_birthday"];
                                                    $contact_data['name'] = $contact_data['first_name']." ".$contact_data['surname'];
                                                    $contact->setFromAttributes($contact_data);
                                                    $contact->save();

                                                    //Home form
                                                    if($contact_data['h_address'] != "")
                                                        $contact->addAddress($contact_data['h_address'], $contact_data['h_city'], $contact_data['h_state'], $contact_data['h_country'], $contact_data['h_zipcode'], 'home');
                                                    if($contact_data['h_phone_number'] != "") $contact->addPhone($contact_data['h_phone_number'], 'home', true);
                                                    if($contact_data['h_phone_number2'] != "") $contact->addPhone($contact_data['h_phone_number2'], 'home');
                                                    if($contact_data['h_mobile_number'] != "") $contact->addPhone($contact_data['h_mobile_number'], 'mobile');
                                                    if($contact_data['h_fax_number'] != "") $contact->addPhone($contact_data['h_fax_number'], 'fax');
                                                    if($contact_data['h_pager_number'] != "") $contact->addPhone($contact_data['h_pager_number'], 'pager');
                                                    if($contact_data['h_web_page'] != "") $contact->addWebpage($contact_data['h_web_page'], 'personal');

                                                    //Work form
                                                    if($contact_data['w_address'] != "")
                                                        $contact->addAddress($contact_data['w_address'], $contact_data['w_city'], $contact_data['w_state'], $contact_data['w_country'], $contact_data['w_zipcode'], 'work');
                                                    if($contact_data['w_phone_number'] != "") $contact->addPhone($contact_data['w_phone_number'], 'work', true);
                                                    if($contact_data['w_phone_number2'] != "") $contact->addPhone($contact_data['w_phone_number2'], 'work');
                                                    if($contact_data['w_assistant_number'] != "") $contact->addPhone($contact_data['w_assistant_number'], 'assistant');
                                                    if($contact_data['w_callback_number'] != "") $contact->addPhone($contact_data['w_callback_number'], 'callback');
                                                    if($contact_data['w_fax_number'] != "") $contact->addPhone($contact_data['w_fax_number'], 'fax', true);
                                                    if($contact_data['w_web_page'] != "") $contact->addWebpage($contact_data['w_web_page'], 'work');

                                                    //Other form
                                                    if($contact_data['o_address'] != "")
                                                        $contact->addAddress($contact_data['o_address'], $contact_data['o_city'], $contact_data['o_state'], $contact_data['o_country'], $contact_data['o_zipcode'], 'other');
                                                    if($contact_data['o_phone_number'] != "") $contact->addPhone($contact_data['o_phone_number'], 'other', true);
                                                    if($contact_data['o_phone_number2'] != "") $contact->addPhone($contact_data['o_phone_number2'], 'other');
                                                    if($contact_data['o_web_page'] != "") $contact->addWebpage($contact_data['o_web_page'], 'other');

                                                    //Emails and instant messaging form
                                                    if($contact_data['email'] != "") $contact->addEmail($contact_data['email'], 'personal', true);
                                                    if($contact_data['email2'] != "") $contact->addEmail($contact_data['email2'], 'personal');
                                                    if($contact_data['email3'] != "") $contact->addEmail($contact_data['email3'], 'personal');

                                                    ApplicationLogs::createLog($contact, null, $log_action);
                                                    $import_result['import_ok'][] = $contact_data;
                                            } else {
                                                    throw new Exception(lang('no access permissions'));
                                            }
                                            DB::commit();					
                                    } catch (Exception $e) {
                                            DB::rollback();
                                            $fail_msg = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n"));
                                            $import_result['import_fail'][] = array('first_name' => $fname, 'surname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status'], 'fail_message' => $fail_msg);
                                    }
                            }
                            $_SESSION['go_back'] = true;
                            tpl_assign('import_result', $import_result);
                        }
                    }
                        
	}
 private function SaveContentToFilesystem($uid, &$content)
 {
     $tmp = ROOT . '/tmp/' . rand();
     $handle = fopen($tmp, "wb");
     fputs($handle, $content);
     fclose($handle);
     $date = DateTimeValueLib::now()->format("Y_m_d_H_i_s__");
     $repository_id = FileRepository::addFile($tmp, array('name' => $date . $uid, 'type' => 'text/plain', 'size' => strlen($content)));
     unlink($tmp);
     return $repository_id;
 }
 /**
  * Set contact picture from $source file
  *
  * @param string $source Source file
  * @param integer $max_width Max picture widht
  * @param integer $max_height Max picture height
  * @param boolean $save Save user object when done
  * @return string
  */
 function setPicture($source, $fileType, $max_width = 50, $max_height = 50, $save = true)
 {
     if (!is_readable($source)) {
         return false;
     }
     do {
         $temp_file = ROOT . '/cache/' . sha1(uniqid(rand(), true));
     } while (is_file($temp_file));
     Env::useLibrary('simplegd');
     $image = new SimpleGdImage($source);
     if ($image->getImageType() == IMAGETYPE_PNG) {
         if ($image->getHeight() > 128 || $image->getWidth() > 128) {
             //	resize images if are png bigger than 128 px
             $thumb = $image->scale($max_width, $max_height, SimpleGdImage::BOUNDARY_DECREASE_ONLY, false);
             $thumb->saveAs($temp_file, IMAGETYPE_PNG);
             $public_fileId = FileRepository::addFile($temp_file, array('type' => 'image/png', 'public' => true));
         } else {
             //keep the png as it is.
             $public_fileId = FileRepository::addFile($source, array('type' => 'image/png', 'public' => true));
         }
     } else {
         $thumb = $image->scale($max_width, $max_height, SimpleGdImage::BOUNDARY_DECREASE_ONLY, false);
         $thumb->saveAs($temp_file, IMAGETYPE_PNG);
         $public_fileId = FileRepository::addFile($temp_file, array('type' => 'image/png', 'public' => true));
     }
     if ($public_fileId) {
         $this->setPictureFile($public_fileId);
         if ($save) {
             $this->save();
         }
         // if
     }
     // if
     $result = true;
     // Cleanup
     if (!$result && $public_fileId) {
         FileRepository::deleteFile($public_fileId);
     }
     // if
     @unlink($temp_file);
     return $result;
 }
 /**
  * This function will process uploaded file
  *
  * @param array $uploaded_file
  * @param boolean $create_revision Create new revision or update last one
  * @param string $revision_comment Revision comment, if any
  * @return ProjectFileRevision
  */
 function handleUploadedFile($uploaded_file, $create_revision = true, $revision_comment = '')
 {
     $revision = null;
     if (!$create_revision) {
         $revision = $this->getLastRevision();
     }
     // if
     if (!$revision instanceof ProjectFileRevision) {
         $revision = new ProjectFileRevision();
         $revision->setFileId($this->getId());
         $revision->setRevisionNumber($this->getNextRevisionNumber());
         if (trim($revision_comment) == '' && $this->countRevisions() < 1) {
             $revision_comment = lang('initial versions');
         }
         // if
     }
     // if
     $revision->deleteThumb(false);
     // remove thumb
     // We have a file to handle!
     if (!is_array($uploaded_file) || !isset($uploaded_file['name']) || !isset($uploaded_file['size']) || !isset($uploaded_file['type']) || !isset($uploaded_file['tmp_name']) || !is_readable($uploaded_file['tmp_name'])) {
         throw new InvalidUploadError($uploaded_file);
     }
     // if
     if (isset($uploaded_file['error']) && $uploaded_file['error'] > UPLOAD_ERR_OK) {
         throw new InvalidUploadError($uploaded_file);
     }
     // if
     $repository_id = FileRepository::addFile($uploaded_file['tmp_name'], array('name' => $uploaded_file['name'], 'type' => $uploaded_file['type'], 'size' => $uploaded_file['size']));
     $revision->setRepositoryId($repository_id);
     $revision->deleteThumb(false);
     $revision->setFilesize($uploaded_file['size']);
     $revision->setFilename($uploaded_file['name']);
     $revision->setTypeString($uploaded_file['type']);
     $extension = get_file_extension(basename($uploaded_file['name']));
     if (trim($extension)) {
         $file_type = FileTypes::getByExtension($extension);
         if ($file_type instanceof Filetype) {
             $revision->setFileTypeId($file_type->getId());
         }
         // if
     }
     // if
     $revision->setComment($revision_comment);
     $revision->save();
     $this->last_revision = $revision;
     // update last revision
     return $revision;
 }
	/**
	 * Execute the script
	 *
	 * @param void
	 * @return boolean
	 */
	function execute() {

		// ---------------------------------------------------
		//  Check MySQL version
		// ---------------------------------------------------

		$mysql_version = mysql_get_server_info($this->database_connection);
		if($mysql_version && version_compare($mysql_version, '4.1', '>=')) {
			$constants['DB_CHARSET'] = 'utf8';
			@mysql_query("SET NAMES 'utf8'", $this->database_connection);
			tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci');
			tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci');
		} else {
			tpl_assign('default_collation', $default_collation = '');
			tpl_assign('default_charset', $default_charset = '');
		} // if

		tpl_assign('table_prefix', TABLE_PREFIX);
		if (defined('DB_ENGINE'))
		tpl_assign('engine', DB_ENGINE);
		else
		tpl_assign('engine', 'InnoDB');

		// ---------------------------------------------------
		//  Execute migration
		// ---------------------------------------------------
		
		// RUN QUERIES
		$total_queries = 0;
		$executed_queries = 0;
		$installed_version = installed_version();
		if (version_compare($installed_version, $this->getVersionFrom()) <= 0) {
			// upgrading from a version lower than this script's 'from' version
			$upgrade_script = tpl_fetch(get_template_path('db_migration/1_5_figazza'));
		} else {
			// upgrading from a pre-release of this version (beta, rc, etc)
			$upgrade_script = "";
			if (version_compare($installed_version, "1.5-beta3") < 0) {
				$upgrade_script .= "
				  ALTER TABLE `".TABLE_PREFIX."users` ADD COLUMN `can_manage_time` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0;
				  ALTER TABLE `".TABLE_PREFIX."groups` ADD COLUMN `can_manage_time` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0;
				";
			}
			if (version_compare($installed_version, "1.5-rc") < 0) {
				$upgrade_script .= "
					INSERT INTO `".TABLE_PREFIX."config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES
						('mailing', 'smtp_address', '', 'StringConfigHandler', 0, 0, '')
					ON DUPLICATE KEY UPDATE id=id;
				";
			}
			$upgrade_script .= "
				DELETE FROM `".TABLE_PREFIX."cron_events` WHERE `name` = 'backup';
				INSERT INTO `".TABLE_PREFIX."user_ws_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES 
					('mails panel', 'email_polling', '0', 'IntegerConfigHandler', '1', '0', NULL),
					('mails panel', 'show_unread_on_title', '0', 'BoolConfigHandler', '1', '0', NULL)
				ON DUPLICATE KEY UPDATE id=id;
			";
		}
		
		$upgrade_script .= "
			ALTER TABLE `".TABLE_PREFIX."mail_accounts` MODIFY COLUMN `del_from_server` INTEGER NOT NULL default 0;
		";

		if (version_compare($installed_version, '1.4.4') < 0) {
			$upgrade_script .= "
				ALTER TABLE `".TABLE_PREFIX."project_tasks`
				 ADD COLUMN `repeat_end` DATETIME NOT NULL default '0000-00-00 00:00:00',
				 ADD COLUMN `repeat_forever` tinyint(1) NOT NULL,
				 ADD COLUMN `repeat_num` int(10) unsigned NOT NULL default '0',
				 ADD COLUMN `repeat_d` int(10) unsigned NOT NULL,
				 ADD COLUMN `repeat_m` int(10) unsigned NOT NULL,
				 ADD COLUMN `repeat_y` int(10) unsigned NOT NULL,
				 ADD COLUMN `repeat_by` varchar(15) collate utf8_unicode_ci NOT NULL default '';
			";
		}
		
		if (!$this->checkColumnExists(TABLE_PREFIX.'users', 'updated_by_id', $this->database_connection)) {
			$upgrade_script .= "
				ALTER TABLE `".TABLE_PREFIX."users` ADD COLUMN `updated_by_id` int(10) unsigned default NULL;
			";
		}
		if (!$this->checkColumnExists(TABLE_PREFIX.'reports', 'is_order_by_asc', $this->database_connection)) {
			$upgrade_script = "
				ALTER TABLE `".TABLE_PREFIX."reports` ADD COLUMN `is_order_by_asc` TINYINT(1) $default_collation NOT NULL DEFAULT 1;
				$upgrade_script
			";
		}
		
		// rename gelsheet tables before upgrading if name is wrong and if engine is case sensitive
		if ($this->checkTableExists(TABLE_PREFIX.'gs_fontStyles', $this->database_connection) && !$this->checkTableExists(TABLE_PREFIX.'gs_fontstyles', $this->database_connection)) {
			$upgrade_script = "
				RENAME TABLE `" . TABLE_PREFIX . "gs_fontStyles` TO `" . TABLE_PREFIX . "gs_fontstyles`;
			" . $upgrade_script;
		}
		if ($this->checkTableExists(TABLE_PREFIX.'gs_mergedCells', $this->database_connection) && !$this->checkTableExists(TABLE_PREFIX.'gs_mergedcells', $this->database_connection)) {
			$upgrade_script = "
				RENAME TABLE `" . TABLE_PREFIX . "gs_mergedCells` TO `" . TABLE_PREFIX . "gs_mergedcells`;
			" . $upgrade_script;
		}

		if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
			$this->printMessage("Database schema transformations executed (total queries: $total_queries)");
		} else {
			$this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
			return false;
		} // if
		
		// UPGRADE CUSTOM PROPERTY MULTIPLE VALUES
		if (version_compare($installed_version, $this->getVersionFrom()) <= 0) {
			$res = mysql_query("SELECT * FROM `".TABLE_PREFIX."custom_property_values` WHERE `custom_property_id` IN (SELECT `id` FROM `".TABLE_PREFIX."custom_properties` WHERE `is_multiple_values` = 1)");
			while ($row = mysql_fetch_assoc($res)) {
				$id = $row['id'];
				$cid = $row['custom_property_id'];
				$oid = $row['object_id'];
				$value = $row['value'];
				$values = explode(",", $value);
				$valuestrings = array();
				foreach ($values as $val) {
					$valuestrings[] = "($oid, $cid, '$val')";
				}
				$valuestring = implode(",", $valuestrings);
				mysql_query("INSERT INTO `".TABLE_PREFIX."custom_property_values` (`object_id`, `custom_property_id`, `value`) VALUES $valuestring");
				mysql_query("DELETE FROM `".TABLE_PREFIX."custom_property_values` WHERE `id` = $id");
			}
		}
		
		// UPGRADE PUBLIC FILES
		if (version_compare($installed_version, $this->getVersionFrom()) <= 0) {
			// load FileRepository classes
			include_once ROOT . "/environment/library/database/adapters/AbstractDBAdapter.class.php";
			include_once ROOT . "/environment/library/database/DB.class.php";
			include_once ROOT . "/environment/library/database/DBResult.class.php";
			include_once ROOT . "/environment/classes/Inflector.class.php";
			include_once ROOT . "/library/filerepository/FileRepository.class.php";
			include_once ROOT . "/library/filerepository/errors/FileNotInRepositoryError.class.php";
			include_once ROOT . "/library/filerepository/errors/FileRepositoryAddError.class.php";
			include_once ROOT . "/library/filerepository/errors/FileRepositoryDeleteError.class.php";
			include_once ROOT . "/library/filerepository/backend/FileRepository_Backend.class.php";
			DB::connect(DB_ADAPTER, array(
				'host'    => DB_HOST,
				'user'    => DB_USER,
				'pass'    => DB_PASS,
				'name'    => DB_NAME,
				'persist' => DB_PERSIST
			)); // connect
			if(defined('DB_CHARSET') && trim(DB_CHARSET)) {
				DB::execute("SET NAMES ?", DB_CHARSET);
			} // if
			$res = mysql_query("SELECT `value` FROM `".TABLE_PREFIX."config_options` WHERE `name` = 'file_storage_adapter'");
			$row = mysql_fetch_assoc($res);
			$adapter = $row['value'];
			if ($adapter == 'mysql') {
				include_once ROOT . "/library/filerepository/backend/FileRepository_Backend_DB.class.php";
				FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX));
			} else {
				include_once ROOT . "/library/filerepository/backend/FileRepository_Backend_FileSystem.class.php";
				FileRepository::setBackend(new FileRepository_Backend_FileSystem(ROOT . "/upload", TABLE_PREFIX));
			}
			$res = mysql_query("SELECT `id`, `avatar_file` FROM `".TABLE_PREFIX."users` WHERE `avatar_file` <> ''", $this->database_connection);
			$count = 0;
			while ($row = mysql_fetch_assoc($res)) {
				$avatar = $row['avatar_file'];
				$id = $row['id'];
				$path = ROOT . "/public/files/$avatar";
				if (is_file($path)) {
					$fid = FileRepository::addFile($path, array('type' => 'image/png'));
					mysql_query("UPDATE `".TABLE_PREFIX."users` SET `avatar_file` = '$fid' WHERE `id` = $id", $this->database_connection);
					$count++;
				}
			}
			$res = mysql_query("SELECT `id`, `picture_file` FROM `".TABLE_PREFIX."contacts` WHERE `picture_file` <> ''", $this->database_connection);
			while ($row = mysql_fetch_assoc($res)) {
				$picture = $row['picture_file'];
				$id = $row['id'];
				$path = ROOT . "/public/files/$picture";
				if (is_file($path)) {
					$fid = FileRepository::addFile($path, array('type' => 'image/png'));
					mysql_query("UPDATE `".TABLE_PREFIX."contacts` SET `picture_file` = '$fid' WHERE `id` = $id", $this->database_connection);
					$count++;
				}
			}
			$res = mysql_query("SELECT `id`, `logo_file` FROM `".TABLE_PREFIX."companies` WHERE `logo_file` <> ''", $this->database_connection);
			while ($row = mysql_fetch_assoc($res)) {
				$logo = $row['logo_file'];
				$id = $row['id'];
				$path = ROOT . "/public/files/$logo";
				if (is_file($path)) {
					$fid = FileRepository::addFile($path, array('type' => 'image/png'));
					mysql_query("UPDATE `".TABLE_PREFIX."companies` SET `logo_file` = '$fid' WHERE `id` = $id", $this->database_connection);
					$count++;
				}
			}
			$this->printMessage("$count public files migrated to upload directory.");
		}
		
		$this->printMessage('Feng Office has been upgraded. You are now running Feng Office '.$this->getVersionTo().' Enjoy!');
	} // execute
 function import_from_vcard()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     @set_time_limit(0);
     ini_set('auto_detect_line_endings', '1');
     if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) {
         unset($_SESSION['go_back']);
     }
     if (isset($_SESSION['go_back'])) {
         unset($_SESSION['go_back']);
         ajx_current("start");
     }
     tpl_assign('import_type', 'contact');
     if (!Contact::canAdd(logged_user(), active_or_personal_project())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $this->setTemplate('vcard_import');
     $filedata = array_var($_FILES, 'vcard_file');
     if (is_array($filedata) && !array_var($_GET, 'step2')) {
         $filename = ROOT . '/tmp/' . logged_user()->getId() . 'temp.vcf';
         copy($filedata['tmp_name'], $filename);
         //ajx_current("empty");
     } else {
         if (array_var($_GET, 'step2')) {
             $filename = ROOT . '/tmp/' . logged_user()->getId() . 'temp.vcf';
             $result = $this->read_vcard_file($filename);
             unlink($filename);
             $import_result = array('import_ok' => array(), 'import_fail' => array());
             foreach ($result as $contact_data) {
                 try {
                     DB::beginWork();
                     if (isset($contact_data['photo_tmp_filename'])) {
                         $file_id = FileRepository::addFile($contact_data['photo_tmp_filename'], array('public' => true));
                         $contact_data['picture_file'] = $file_id;
                         unlink($contact_data['photo_tmp_filename']);
                         unset($contact_data['photo_tmp_filename']);
                     }
                     if (isset($contact_data['company_name'])) {
                         $company = Companies::findOne(array("conditions" => "`name` = '" . mysql_real_escape_string($contact_data['company_name']) . "'"));
                         if ($company == null) {
                             $company = new Company();
                             $company->setName($contact_data['company_name']);
                             $company->setClientOfId(logged_user()->getCompanyId());
                             $company->save();
                             ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                         }
                         $contact_data['company_id'] = $company->getId();
                         unset($contact_data['company_name']);
                     }
                     $contact_data['import_status'] = '(' . lang('updated') . ')';
                     $fname = mysql_real_escape_string(array_var($contact_data, "firstname"));
                     $lname = mysql_real_escape_string(array_var($contact_data, "lastname"));
                     $contact = Contacts::findOne(array("conditions" => "firstname = '" . $fname . "' AND lastname = '" . $lname . "' OR email <> '' AND email = '" . array_var($contact_data, "email") . "'"));
                     $log_action = ApplicationLogs::ACTION_EDIT;
                     if (!$contact) {
                         $contact = new Contact();
                         $contact_data['import_status'] = '(' . lang('new') . ')';
                         $log_action = ApplicationLogs::ACTION_ADD;
                         $can_import = active_project() != null ? $contact->canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user());
                     } else {
                         $can_import = $contact->canEdit(logged_user());
                     }
                     if ($can_import) {
                         $contact->setFromAttributes($contact_data);
                         $contact->save();
                         ApplicationLogs::createLog($contact, null, $log_action);
                         $contact->setTagsFromCSV(array_var($_GET, 'tags'));
                         if (active_project() instanceof Project) {
                             $pc = ProjectContacts::findOne(array("conditions" => "contact_id = " . $contact->getId() . " AND project_id = " . active_project()->getId()));
                             if (!$pc) {
                                 $pc = new ProjectContact();
                                 $pc->setContactId($contact->getId());
                                 $pc->setProjectId(active_project()->getId());
                                 $pc->setRole(array_var($contact_data, 'role'));
                                 $pc->save();
                             }
                             $contact->addToWorkspace(active_project());
                         }
                         $import_result['import_ok'][] = array('firstname' => $fname, 'lastname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status']);
                     } else {
                         throw new Exception(lang('no access permissions'));
                     }
                     DB::commit();
                 } catch (Exception $e) {
                     DB::rollback();
                     $fail_msg = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n"));
                     $import_result['import_fail'][] = array('firstname' => $fname, 'lastname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status'], 'fail_message' => $fail_msg);
                 }
             }
             $_SESSION['go_back'] = true;
             tpl_assign('import_result', $import_result);
         }
     }
 }