Example #1
0
<?php

/**
 * @package Newscoop
 */
require_once $GLOBALS['g_campsiteDir'] . '/classes/Input.php';
require_once $GLOBALS['g_campsiteDir'] . '/classes/Image.php';
require_once $GLOBALS['g_campsiteDir'] . '/classes/ImageSearch.php';
require_once $GLOBALS['g_campsiteDir'] . '/classes/Log.php';
$translator = \Zend_Registry::get('container')->getService('translator');
// TODO: permissions
if (!is_writable($Campsite['IMAGE_DIRECTORY'])) {
    camp_html_add_msg($translator->trans('Unable to add new image, target directory is not writable.', array(), 'users'));
    camp_html_add_msg(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $Campsite['IMAGE_DIRECTORY']));
    camp_html_goto_page("/{$ADMIN}/");
    exit;
}
if (!$g_user->hasPermission('EditAuthors')) {
    camp_html_display_error($translator->trans('You do not have the permission to change authors.', array(), 'users'));
    exit;
}
$id = Input::Get('id', 'int', -1);
// Delete author
$del_id = Input::Get('del_id', 'int', -1);
if ($del_id > -1) {
    $author = new Author($del_id);
    if ($author->delete()) {
        camp_html_add_msg($translator->trans('Author deleted.', array(), 'users'), 'ok');
    }
}
// Add new author type
Example #2
0
 /**
  * This function should be called when an attachment is uploaded.  It will
  * save the attachment to the appropriate place on the disk, and create a
  * database entry for the file.
  *
  * @param array $p_fileVar
  *     <pre>
  * 		The variable from the $_FILES array.  The array specifies the following:
  *		$a["name"] = original name of the file.
  * 		$a["type"] = the MIME type of the file
  *		$a["tmp_name"] = the temporary storage location on disk of the file
  *		$a["size"] = size of the file, in bytes (not required)
  *		$a["error"] = 0 (zero) if there was no error
  *     </pre>
  *
  * @param array $p_attributes
  *		Optional attributes which are stored in the database.
  *		Indexes can be the following: 'content_disposition', 'fk_language_id', 'http_charset', 'fk_user_id'
  *
  * @param int $p_id
  *		If the attachment already exists and we just want to update it, specify the
  *		current ID here.
  *
  * @param bool $p_uploaded
  *      If the attachment was uploaded with other mechanism (ex: plUploader)
  *      this is set so that the single upload file from article functionality is still secured.
  *
  * @return mixed
  *		The Attachment object that was created or updated.
  *		Return a PEAR_Error on failure.
  */
 public static function OnFileUpload($p_fileVar, $p_attributes, $p_id = null, $p_uploaded = false)
 {
     if (!is_array($p_fileVar)) {
         return null;
     }
     // Verify its a valid file.
     $filesize = filesize($p_fileVar['tmp_name']);
     if ($filesize === false) {
         return new PEAR_Error("Attachment::OnFileUpload(): invalid parameters received.");
     }
     // Are we updating or creating?
     if (!is_null($p_id)) {
         // Updating the attachment
         $attachment = new Attachment($p_id);
         $attachment->update($p_attributes);
         // Remove the old file because
         // the new file may have a different file extension.
         if (file_exists($attachment->getStorageLocation())) {
             unlink($attachment->getStorageLocation());
         }
     } else {
         // Creating the attachment
         $attachment = new Attachment();
         $attachment->create($p_attributes);
         $attachment->setProperty('time_created', 'NULL', true, true);
     }
     $attachment->setProperty('file_name', $p_fileVar['name'], false);
     $attachment->setProperty('mime_type', $p_fileVar['type'], false);
     $attachment->setProperty('size_in_bytes', $p_fileVar['size'], false);
     $extension = "";
     $fileParts = explode('.', $p_fileVar['name']);
     if (count($fileParts) > 1) {
         $extension = array_pop($fileParts);
         $attachment->setProperty('extension', $extension, false);
     }
     $target = $attachment->getStorageLocation();
     $attachment->makeDirectories();
     ob_start();
     var_dump(is_uploaded_file($p_fileVar['tmp_name']));
     $dump = ob_get_clean();
     /**
      * for security reason
      *  for file uploaded normal not with other mechanism (ex: plUploader)
      *  we still need the move_uploaded_file functionality
      */
     if (!$p_uploaded && !move_uploaded_file($p_fileVar['tmp_name'], $target)) {
         $attachment->delete();
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $target), CAMP_ERROR_CREATE_FILE);
     }
     // if the file was uploaded with other mechanism (ex: plUploader) use rename(move) functionality
     if ($p_uploaded && !rename($p_fileVar['tmp_name'], $target)) {
         $attachment->delete();
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $target), CAMP_ERROR_CREATE_FILE);
     }
     chmod($target, 0644);
     $attachment->commit();
     return $attachment;
 }
Example #3
0
 /**
  * @param p_oFile
  * @param p_dFile
  * @param p_type
  * @param p_charset
  *
  * @return
  */
 public static function ChangeCharset($p_oFile, $p_dFile, $p_type, $p_charset)
 {
     if (strncmp($p_type, 'text', 4) == 0) {
         $origFile = $p_dFile . '.orig';
         $success = rename($p_oFile, $origFile);
         if ($success) {
             $command = 'iconv -f ' . escapeshellarg($p_charset) . ' -t UTF-8 ' . escapeshellarg($origFile) . ' > ' . escapeshellarg($p_dFile);
             system($command, $status);
             if ($status == 0) {
                 $success = unlink($origFile);
             } else {
                 $success = false;
                 unlink($p_dFile);
                 return new PEAR_Error("Unable to convert the character set of the file.");
             }
         } else {
             return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $origFile), CAMP_ERROR_CREATE_FILE);
         }
     }
     return $success;
 }
Example #4
0
	/**
	 * Download the remote file and save it to disk, create a thumbnail for it,
	 * and create a database entry for the file.
	 *
	 * @param string $p_url
	 *		The remote location of the file. ("http://...");
	 *
	 * @param array $p_attributes
	 *		Optional attributes which are stored in the database.
	 *		Indexes can be the following: 'Description', 'Photographer', 'Place', 'Date'
	 *
	 * @param int $p_userId
	 *		The user ID of the user who uploaded the image.
	 *
	 * @param int $p_id
	 *		If you are updating an image, specify its ID here.
	 *
	 * @return mixed
	 * 		Return an Image object on success, return a PEAR_Error otherwise.
	 */
	public static function OnAddRemoteImage($p_url, $p_attributes,
	                                        $p_userId = null, $p_id = null)
	{
		global $Campsite;
		if (function_exists("camp_load_translation_strings")) {
			camp_load_translation_strings("api");
		}

		// Check if thumbnail directory is writable.
		$imageDir = $Campsite['IMAGE_DIRECTORY'];
		$thumbDir = $Campsite['THUMBNAIL_DIRECTORY'];
		if (!file_exists($imageDir) || !is_writable($imageDir)) {
			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $imageDir), CAMP_ERROR_WRITE_DIR);
		}
		if (!file_exists($thumbDir) || !is_writable($thumbDir)) {
			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $thumbDir), CAMP_ERROR_WRITE_DIR);
		}

		$client = new HTTP_Client();
	    $client->get($p_url);
	    $response = $client->currentResponse();
	    if ($response['code'] != 200) {
	    	return new PEAR_Error(getGS("Unable to fetch image from remote server."));
	    }
	    foreach ($response['headers'] as $headerName => $value) {
	    	if (strtolower($headerName) == "content-type") {
	    		$ContentType = $value;
	    		break;
	    	}
	    }

        // Check content type
        if (!preg_match('/image/', $ContentType)) {
            // wrong URL
            return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url));
        }

    	// Save the file
        $tmpname = $Campsite['TMP_DIRECTORY'].'img'.md5(rand());
        if (is_writable($Campsite['TMP_DIRECTORY'])) {
	        if ($tmphandle = fopen($tmpname, 'w')) {
	            fwrite($tmphandle, $response['body']);
	            fclose($tmphandle);
	        }
        } else {
	    	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE);
	    }

        // Check if it is really an image file
        $imageInfo = getimagesize($tmpname);
        if ($imageInfo === false) {
        	unlink($tmpname);
            return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL));
        }

        // content-type = image
        if (!is_null($p_id)) {
        	// Updating the image
        	$image = new Image($p_id);
        	$image->update($p_attributes);
	    	// Remove the old image & thumbnail because
	    	// the new file might have a different file extension.
	    	if (file_exists($image->getImageStorageLocation())) {
				if (is_writable(dirname($image->getImageStorageLocation()))) {
		    		unlink($image->getImageStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
	    	if (file_exists($image->getThumbnailStorageLocation())) {
				if (is_writable(dirname($image->getThumbnailStorageLocation()))) {
		    		unlink($image->getThumbnailStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
        } else {
        	// Creating the image
        	$image = new Image();
        	$image->create($p_attributes);
        	$image->setProperty('TimeCreated', 'NULL', true, true);
        	$image->setProperty('LastModified', 'NULL', true, true);
        }
        if (!isset($p_attributes['Date'])) {
        	$image->setProperty('Date', 'NOW()', true, true);
        }
        $image->setProperty('Location', 'remote', false);
        $image->setProperty('URL', $p_url, false);
	    if (isset($imageInfo['mime'])) {
	    	$image->setProperty('ContentType', $imageInfo['mime'], false);
	    }

        // Remember who uploaded the image
        if (!is_null($p_userId)) {
			$image->setProperty('UploadedByUser', $p_userId, false);
        }

        if ($Campsite['IMAGEMAGICK_INSTALLED']) {
		    // Set thumbnail file name
		    $extension = Image::__ImageTypeToExtension($imageInfo[2]);
		    $thumbnail = $image->generateThumbnailStorageLocation($extension);
		    $image->setProperty('ThumbnailFileName', basename($thumbnail), false);

		    if (!is_writable(dirname($image->getThumbnailStorageLocation()))) {
            	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE);
		    }

		    // Create the thumbnail
            $cmd = $Campsite['THUMBNAIL_COMMAND'].' '
            	. $tmpname . ' ' . $image->getThumbnailStorageLocation();
            system($cmd);
            if (file_exists($image->getThumbnailStorageLocation())) {
            	chmod($image->getThumbnailStorageLocation(), 0644);
            }
        }
        unlink($tmpname);
        $image->commit();

		$logtext = getGS('The image $1 has been added.',
						$image->m_data['Description']." (".$image->m_data['Id'].")");
		Log::Message($logtext, null, 41);

	    return $image;
	} // fn OnAddRemoteImage
    /**
     * Save the translation table to a PHP-GS file.
     *
     * @param LocalizerLanguage $p_localizerLanguage
     *		LocalizerLanguage object.
     *
     * @return int
     *		CAMP_SUCCESS
     * 		CAMP_ERROR_MKDIR
     * 		CAMP_ERROR_WRITE_FILE
     */
	function save(&$p_localizerLanguage)
	{
	    global $g_localizerConfig;
    	$data = "<?php \n";
    	$translationTable = $p_localizerLanguage->getTranslationTable();
    	foreach ($translationTable as $key => $value) {
    	    // Escape quote characters.
    	    $key = str_replace('"', '\"', $key);
    	    $value = str_replace('"', '\"', $value);
    	    // do not insert $key and $value variables in between double quotes
    	    // escape sequences may be interpreted and this will modify the string
    	    $data .= "regGS(\"" . $key . "\", \"" . $value . "\");\n";
    	}
    	$data .= "?>";
        $filePath = LocalizerFileFormat_GS::GetFilePath($p_localizerLanguage);
        $p_localizerLanguage->_setSourceFile($filePath);

        // Create the language directory if it doesnt exist.
        $country = $p_localizerLanguage->getCountryCode() ? '_' : null;
        if (substr($p_localizerLanguage->m_prefix, 0, 7) == 'plugin_') {
            // use the plugin storage location
            $pluginName = str_replace('plugin_', '', $p_localizerLanguage->m_prefix);
	        $dirName = CS_PATH_PLUGINS.DIR_SEP.$pluginName.DIR_SEP.'admin-files'.DIR_SEP.'lang'.DIR_SEP
	        .$p_localizerLanguage->getLanguageCode().$country.$p_localizerLanguage->getCountryCode();
        } else {
            // use the default storage location
            $dirName = $g_localizerConfig['TRANSLATION_DIR'].'/'.$p_localizerLanguage->getLanguageCode()
            .$country.$p_localizerLanguage->getCountryCode();
        }

        if (!file_exists($dirName)) {
        	if (is_writable(dirname($dirName))) {
            	mkdir($dirName);
        	} else {
        		return new PEAR_Error(camp_get_error_message(CAMP_ERROR_MKDIR, $dirName), CAMP_ERROR_MKDIR);
        	}
        }

        // Write data to the file
        if (!file_exists($filePath)) {
        	if (is_writable($dirName)) {
		        File::write($filePath, $data, FILE_MODE_WRITE);
	        } else {
	        	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_FILE, $filePath), CAMP_ERROR_WRITE_FILE);
	        }
        } else {
	        if (is_writable($filePath)) {
		        File::write($filePath, $data, FILE_MODE_WRITE);
	        } else {
	        	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_FILE, $filePath), CAMP_ERROR_WRITE_FILE);
	        }
        }
        File::close($filePath, FILE_MODE_WRITE);
        return CAMP_SUCCESS;
    } // fn save
Example #6
0
require_once($GLOBALS['g_campsiteDir']. "/$ADMIN_DIR/templates/template_common.php");

if (!$g_user->hasPermission('ManageTempl')) {
	camp_html_display_error(getGS("You do not have the right to create folders."));
	exit;
}

$Path = Input::Get('Path', 'string', '');
if (!Template::IsValidPath($Path)) {
	camp_html_goto_page("/$ADMIN/templates/");
}

$fullPath = $Campsite['TEMPLATE_DIRECTORY'].$Path;
if (!is_writable($fullPath)) {
	camp_html_add_msg(getGS("Unable to create folder."));
	camp_html_add_msg(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $fullPath));
	camp_html_goto_page("/$ADMIN/templates/?Path=".urlencode($Path));
	exit;
}

$crumbs = array();
$crumbs[] = array(getGS("Configure"), "");
$crumbs[] = array(getGS("Templates"), "/$ADMIN/templates/");
$crumbs = array_merge($crumbs, camp_template_path_crumbs($Path));
$crumbs[] = array(getGS("Create new folder"), "");
echo camp_html_breadcrumbs($crumbs);

include_once($GLOBALS['g_campsiteDir']."/$ADMIN_DIR/javascript_common.php");

camp_html_display_msgs();
?>
Example #7
0
 /**
  * Saves the image refered by the resource handler to a file
  *
  * @param  resource $p_image
  *                                  Image resource handler
  * @param  string   $p_fileName
  *                                  The full path of the file
  * @param  int      $p_type
  *                                  The image type
  * @param  bool     $p_addExtension
  *                                  If true it will add the proper extension to the file name.
  * @return mixed
  *                                 true if successful, PEAR_Error object in case of error
  */
 public static function SaveImageToFile($p_image, $p_fileName, $p_imageType, $p_addExtension = true)
 {
     $translator = \Zend_Registry::get('container')->getService('translator');
     $method = null;
     switch ($p_imageType) {
         case IMAGETYPE_GIF:
             $method = 'imagegif';
             break;
         case IMAGETYPE_JPEG:
             $method = 'imagejpeg';
             break;
         case IMAGETYPE_PNG:
             $method = 'imagepng';
             break;
         case IMAGETYPE_WBMP:
             $method = 'imagewbmp';
             break;
         case IMAGETYPE_XBM:
             $method = 'imagexbm';
             break;
     }
     // these are the supported image types
     if ($method == null) {
         return new PEAR_Error($translator->trans("Image type \$1 is not supported.", array('$1' => image_type_to_mime_type($p_imageType)), 'api'));
     }
     if (!$method($p_image, $p_fileName)) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $p_fileName), CAMP_ERROR_CREATE_FILE);
     }
     return true;
 }
Example #8
0
    camp_html_goto_page($backLink);
}
$filename = Template::GetFullPath($f_path, $f_name);
$templateName = (!empty($f_path) ? $f_path."/" : "").$f_name;
if ($templateName[0] == '/') {
    $templateName = substr($templateName, 1);
}
$templateObj = new Template($templateName);

if (!file_exists($filename)) {
    camp_html_display_error(getGS("Invalid template file $1" , $f_path."/$f_name"), $backLink);
    exit;
}

if (!is_writable($filename)) {
    camp_html_add_msg(camp_get_error_message(CAMP_ERROR_WRITE_FILE, $filename));
}

$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$imageExtensions = array("png", "jpg", "jpeg", "jpe", "gif");

$templateDisplayName = $f_name;
if ($templateObj->exists()) {
    $templateDisplayName .= ' ('.getGS("Template ID:").' '.$templateObj->getTemplateId().')';
}

$f_lifetime = (int)$templateObj->getCacheLifetime();

$crumbs = array();
$crumbs[] = array(getGS("Configure"), "");
$crumbs[] = array(getGS("Templates"), "/$ADMIN/templates/");
Example #9
0
 /**
  * Delete language files for the given language.
  * @param string $p_languageCode
  * @return mixed
  * 		Return TRUE on success, PEAR_Error on failure.
  */
 public static function DeleteLanguageFiles($p_languageCode)
 {
     global $g_localizerConfig;
     $langDir = $g_localizerConfig['TRANSLATION_DIR'].'/'.$p_languageCode;
     if (!file_exists($langDir)) {
         return true;
     }
     $files = File_Find::mapTreeMultiple($langDir, 1);
     foreach ($files as $fileName) {
         $pathname = $langDir . DIR_SEP . $fileName;
         if (file_exists($pathname)) {
         	if (is_writable($pathname)) {
             	unlink($pathname);
         	} else {
         		return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $pathname), CAMP_ERROR_DELETE_FILE);
         	}
         }
     }
     @rmdir($langDir);
     return true;
 } // fn DeleteLanguageFiles
Example #10
0
if (!$g_user->hasPermission('DeleteFile')) {
    camp_html_display_error(getGS('You do not have the right to delete files.'), null, true);
    exit;
}
$f_debate_nr = Input::Get('f_debate_nr', 'int', 0);
$f_debateanswer_nr = Input::Get('f_debateanswer_nr', 'int', 0);
$f_fk_language_id = Input::Get('f_fk_language_id', 'int', 0);
$f_attachment_id = Input::Get('f_attachment_id', 'int', 0);
$attachmentObj = new Attachment($f_attachment_id);
if (!$attachmentObj->exists()) {
    camp_html_display_error(getGS('Attachment does not exist.'), null, true);
    exit;
}
$filePath = dirname($attachmentObj->getStorageLocation()) . '/' . $attachmentObj->getFileName();
if (!is_writable(dirname($filePath))) {
    camp_html_add_msg(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $filePath, basename($attachmentObj->getStorageLocation())));
    //camp_html_goto_page(camp_html_article_url($articleObj, $f_language_id, 'edit.php'));
    exit;
}
$DebateAnswerAttachment = new DebateAnswerAttachment($f_debate_nr, $f_debateanswer_nr, $f_attachment_id);
$DebateAnswerAttachment->delete();
// Go back to upload screen.
camp_html_add_msg(getGS("File '\$1' deleted.", $attachmentObj->getFileName()), "ok");
$attachmentObj->delete();
?>
<script>
location.href="popup.php?f_debate_nr=<?php 
p($f_debate_nr);
?>
&f_debateanswer_nr=<?php 
p($f_debateanswer_nr);
Example #11
0
		Log::Message($logtext, $g_user->getUserId(), 112);
		camp_html_add_msg($logtext, "ok");
	} else {
		camp_html_add_msg(camp_get_error_message(CAMP_ERROR_RMDIR, $fileFullPath));
	}
} else {
	$inUse = Template::InUse($fileFullName);
	if ($inUse === CAMP_ERROR_READ_FILE || $inUse === CAMP_ERROR_READ_DIR) {
                camp_html_add_msg(getGS("There are some files which can not be readed so Newscoop was not able to determine whether '$1' is in use or not. Please fix this, then try to delete the template again.", basename($fileFullName)));
	} elseif ($inUse == false) {
	        $template = new Template($fileFullName);
		if ($template->exists() && $template->delete()) {
			// Clear compiled template
			require_once($GLOBALS['g_campsiteDir']."/template_engine/classes/CampTemplate.php");
			CampTemplate::singleton()->clear_compiled_tpl($fileFullName);

			$logtext = getGS('Template object $1 was deleted', mysql_real_escape_string($fileFullName));
			Log::Message($logtext, $g_user->getUserId(), 112);
			camp_html_add_msg($logtext, "ok");
		} else {
			camp_html_add_msg(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $fileFullName));
		}
	} else {
		camp_html_add_msg(getGS("The template object $1 is in use and can not be deleted.", $fileFullName));
	}
}

camp_html_goto_page($backLink);

?>
Example #12
0
$cName = Input::Get('cName', 'string', '');

$backLink = "/$ADMIN/templates/new_dir.php?Path=".urlencode($cPath);

if (trim($cName) == '') {
	camp_html_add_msg(getGS('You must fill in the $1 field.','<B>'.getGS('Name').'</B>'));
	camp_html_goto_page($backLink);
}

if (trim($cName) == '..' || trim($cName) == '.') {
	camp_html_add_msg(getGS("The folder name can't be '..' or '.'"));
	camp_html_goto_page($backLink);
}

$cName = strtr($cName, '?~#%*&|"\'\\/<>', '_____________');
$newdir = Template::GetFullPath($cPath, $cName);
$file_exists = file_exists($newdir);
if (!$file_exists) {
	$dir = mkdir($newdir, 0755);
	if ($dir === true) {
		camp_html_add_msg(getGS("Directory $1 created.", "&quot;".$cName."&quot;"), "ok");
		camp_html_goto_page("/$ADMIN/templates/?Path=" . urlencode("$cPath/$cName"));
	} else {
		camp_html_add_msg(camp_get_error_message(CAMP_ERROR_MKDIR, $newdir));
	}
} else {
	camp_html_add_msg(getGS('A file or folder having the name $1 already exists','&quot;'.$cName.'&quot;'));
}
camp_html_goto_page($backLink);

?>
Example #13
0
 /**
  * Delete language files for the given language.
  * @param string $p_languageCode
  * @return mixed
  * 		Return TRUE on success, PEAR_Error on failure.
  */
 public static function DeleteLanguageFiles($p_languageCode)
 {
     global $g_localizerConfig;
     $langDir = $g_localizerConfig['TRANSLATION_DIR'] . '/' . $p_languageCode;
     if (!file_exists($langDir)) {
         return true;
     }
     $iterator = new DirectoryIterator($langDir);
     foreach ($iterator as $file) {
         if ($file->isDot()) {
             // ignore dots
             continue;
         }
         if (!$file->isWritable()) {
             return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $file->getRealpath()), CAMP_ERROR_DELETE_FILE);
         }
         unlink($file->getRealpath());
     }
     @rmdir($langDir);
     return true;
 }
Example #14
0
 /**
  * Download the remote file and save it to disk, create a thumbnail for it,
  * and create a database entry for the file.
  *
  * @param string $p_url
  *		The remote location of the file. ("http://...");
  *
  * @param array $p_attributes
  *		Optional attributes which are stored in the database.
  *		Indexes can be the following: 'Description', 'Photographer', 'Place', 'Date'
  *
  * @param int $p_userId
  *		The user ID of the user who uploaded the image.
  *
  * @param int $p_id
  *		If you are updating an image, specify its ID here.
  *
  * @return mixed
  * 		Return an Image object on success, return a PEAR_Error otherwise.
  */
 public static function OnAddRemoteImage($p_url, $p_attributes, $p_userId = null, $p_id = null)
 {
     global $Campsite;
     if (function_exists("camp_load_translation_strings")) {
         camp_load_translation_strings("api");
     }
     // Check if thumbnail directory is writable.
     $imageDir = $Campsite['IMAGE_DIRECTORY'];
     $thumbDir = $Campsite['THUMBNAIL_DIRECTORY'];
     if (!file_exists($imageDir) || !is_writable($imageDir)) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $imageDir), CAMP_ERROR_WRITE_DIR);
     }
     if (!file_exists($thumbDir) || !is_writable($thumbDir)) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $thumbDir), CAMP_ERROR_WRITE_DIR);
     }
     // fetch headers
     $headers = get_headers($p_url, TRUE);
     if (strpos($headers[0], '200 OK') === FALSE) {
         return new PEAR_Error(getGS("Unable to fetch image from remote server."));
     }
     // get type
     $ContentType = $headers['Content-Type'];
     // Check content type
     if (strpos($ContentType, 'image') === FALSE) {
         // wrong URL
         return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url));
     }
     // check path
     if (!is_writable($Campsite['TMP_DIRECTORY'])) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE);
     }
     // save image
     $tmpname = $Campsite['TMP_DIRECTORY'] . 'img' . md5(uniqid());
     file_put_contents($tmpname, file_get_contents($p_url));
     // Check if it is really an image file
     $imageInfo = getimagesize($tmpname);
     if ($imageInfo === false) {
         unlink($tmpname);
         return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL));
     }
     // content-type = image
     if (!is_null($p_id)) {
         // Updating the image
         $image = new Image($p_id);
         $image->update($p_attributes);
         // Remove the old image & thumbnail because
         // the new file might have a different file extension.
         if (file_exists($image->getImageStorageLocation())) {
             if (is_writable(dirname($image->getImageStorageLocation()))) {
                 unlink($image->getImageStorageLocation());
             } else {
                 return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE);
             }
         }
         if (file_exists($image->getThumbnailStorageLocation())) {
             if (is_writable(dirname($image->getThumbnailStorageLocation()))) {
                 unlink($image->getThumbnailStorageLocation());
             } else {
                 return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE);
             }
         }
     } else {
         $image = new Image();
         $image->create($p_attributes);
         $image->setProperty('TimeCreated', 'NULL', true, true);
         $image->setProperty('LastModified', 'NULL', true, true);
     }
     if (!isset($p_attributes['Date'])) {
         $image->setProperty('Date', 'NOW()', true, true);
     }
     $image->setProperty('Location', 'remote', false);
     $image->setProperty('URL', $p_url, false);
     if (isset($imageInfo['mime'])) {
         $image->setProperty('ContentType', $imageInfo['mime'], false);
     }
     // Remember who uploaded the image
     if (!is_null($p_userId)) {
         $image->setProperty('UploadedByUser', $p_userId, false);
     }
     // create thumbnail
     $extension = Image::__ImageTypeToExtension($imageInfo[2]);
     $thumbnail = $image->generateThumbnailStorageLocation($extension);
     $image->setProperty('ThumbnailFileName', basename($thumbnail), false);
     if (!is_writable(dirname($thumbnail))) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE);
     }
     $createMethodName = Image::__GetImageTypeCreateMethod($imageInfo[2]);
     if (!isset($createMethodName)) {
         throw new Exception(getGS("Image type \$1 is not supported.", image_type_to_mime_type($ContentType)));
     }
     $imageHandler = $createMethodName($tmpname);
     if (!$imageHandler) {
         throw new Exception(camp_get_error_message(CAMP_ERROR_UPLOAD_FILE, $p_fileVar['name']), CAMP_ERROR_UPLOAD_FILE);
     }
     $thumbnailImage = Image::ResizeImage($imageHandler, $Campsite['THUMBNAIL_MAX_SIZE'], $Campsite['THUMBNAIL_MAX_SIZE']);
     if (PEAR::isError($thumbnailImage)) {
         throw new Exception($thumbnailImage->getMessage(), $thumbnailImage->getCode());
     }
     $result = Image::SaveImageToFile($thumbnailImage, $thumbnail, $imageInfo[2]);
     if (PEAR::isError($result)) {
         throw new Exception($result->getMessage(), $result->getCode());
     }
     if (file_exists($thumbnail)) {
         self::chmod($thumbnail, 0644);
     }
     unlink($tmpname);
     $image->commit();
     return $image;
 }