View source
<?php
$modulepath = drupal_get_path('module', 'webfm');
require_once "./" . $modulepath . "/webfm_file.inc";
require_once "./" . $modulepath . "/webfm_mime_types.inc";
if (function_exists('file_get_mimetype')) {
function webfm_mime_type($filename) {
return file_get_mimetype($filename);
}
}
else {
function webfm_mime_type($filename) {
return webfm_mime_content_type($filename);
}
}
define('WEBFM_FLUSH', -1);
define('WEBFM_REPLACE_RENAME', 0);
define('WEBFM_REPLACE_DELETE', 1);
define('WEBFM_RENAME_NEW', 2);
define('WEBFM_CANCEL', 3);
define('WEBFM_ADMIN', 1);
define('WEBFM_USER', 2);
define('WEBFM_ATTACH_VIEW', 3);
define('WEBFM_FILE_ACCESS_PUBLIC_VIEW', 1);
define('WEBFM_FILE_ACCESS_ROLE_VIEW', 2);
define('WEBFM_FILE_ACCESS_ROLE_ATTACH', 4);
define('WEBFM_FILE_ACCESS_ROLE_FULL', 8);
define('WEBFM_MAX_FILE_ACCESS', WEBFM_FILE_ACCESS_PUBLIC_VIEW + WEBFM_FILE_ACCESS_ROLE_VIEW + WEBFM_FILE_ACCESS_ROLE_ATTACH + WEBFM_FILE_ACCESS_ROLE_FULL);
define('WEBFM_DATE_FORMAT_DAY', 1);
define('WEBFM_DATE_FORMAT_MONTH', 2);
function webfm_help($section) {
switch ($section) {
case 'admin/help#webfm':
$output = t('
<p>WebFM is a hierarchical file system manager. WebFM does not use a flat file system (a single directory indexed by a database). WebFM allows users to arrange files on the server in the same way they do on their local storage drives. This ability to heirarchically arrange files greatly enhances the managability of large collections of data.</p>
<p>WebFM uses Ajax to provide application intensive functionality such as drag-and-drop and context-sensitive menuing. JavaScript must be enabled for WebFM to function - functionality will not gracefully degrade for clients that have JavaScript disabled.</p>
<h2>Installation & Configuration</h2>
<ul>
<li>Download the official release from the <a href="http://drupal.org/project/webfm">project page</a>.</li>
<li>Unzip the archive and copy the \'webfm\' directory to your modules directory (ie:/sites/all/modules). Alternatively copy the tarball to the module directory if you can unzip it on the server.</li>
<li>Enable the module on Drupal\'s admin/build/modules page. An install file updates the database with the necessary table additions.</li>
<li>Configure the module at admin/settings/webfm. <strong>Note:</strong> The configuration assumes that the \'File system path:\' is set in the usual way at %file-sys. All WebFM directories are sub-directories of this \'File System\' path. Set \'Download method:\' radio to \'Public\' since the module manages downloads.
<ul>
<li>Create the \'WebFM root directory\'. If this directory doesn\'t already exist, the system will create it in the \'File System\' root. Directory creation is not recursive so multi directory root paths must already exist inside the \'File System\' directory. Set the directory permissions to 775 if the server is linux/bsd.</li>
<li>The icon path allows the user to substitute their own gifs. File names are hardcoded in the javascript so the icons will have to have identical names.</li>
<li>The \'Maximum resolution for uploaded images\' input functions in the same fashion as the upload.module.</li>
<li>The \'Date Format\' radio buttons set the day/month order in the browser listing date field.</li>
<li>The \'Display metadata title\' checkbox sets the browser to display metadata titles rather than the actual filename if the metadata tile exists. Renaming files that use the metadata title must be done via the metadata editor. Note that node attachments always display the metadata title if available.</li>
<li>\'Default File Permissions\' set the file level permissions for files inserted into the database. The exception is file uploads that create a version overwrite whereby the new file inherits the permissions from the previous file.</li>
<li>Roles that are granted the \'access webfm\' permission will receive additional configuration fields for root path, extension white list, max upload file size and max total upload size. Roles with the \'access webfm\' right but without a root directory cannot access the filesystem.</li>
<li>Roles granted the \'attach WebFM files\' permission will be able to see and download attached files. \'Attachment List Properties\' sets the presentation of attached files.</li>
<li>The \'IE Drag-and-Drop Normalization\' is a sub-optimal solution for compensating for relative positioning in theme css. This feature is only available to #1 user.</li>
<li>The \'Webfm javascript debug\' checkbox is only useful for users interested in looking under the covers or who want to develop the module.</li>
<li>The WebFM cron is a \'stored procedure\' used for database cleanup of file records that are deleted outside of the WebFM interface (ie: OS shell, ftp). This feature is only available to #1 user.</li>
</ul>
</li>
<li>Set WebFM rights in admin/user/access per role.
<ul>
<li>\'administer webfm\' confers full rights to a role. Admins can see and operate on all files, including files not in the database. Only admins can create directories and access admin/settings/webfm.</li>
<li>\'access webfm\' allows a role to download/view files via the WebFM browser. Only files referenced by the webfm_file table in the database are accessible. Only owners of a file (and admins) can move a file or modify it\'s metadata.</li>
<li>\'view webfm attachments\' allows a role to see files attached to nodes via WebFM.</li>
<li>\'webfm upload\' allows a role with the \'access webfm\' right to upload files via the WebFM browser. The user who uploads a file is the the owner of that file.</li>
</ul>
</li>
<li>Admins and File owners can set the following file level permissions from the context menu of each file:
<ul>
<li>Public download: Allows the file to be downloaded anonymously even if .htaccess exists.</li>
<li>Role View/Download: Allows users of the same role to view/download the file.</li>
<li>Role Attach: Allows users of the same role to attach the file to nodes.</li>
<li>Role Full Access: Allows users of the same role to have the same rights to the file as the owner with the exception of permission edits.</li>
</ul>
</li>
<li>Enable attachments in admin/settings/content-types/*type* for each content type that will accept attachments (default is disabled).</li>
<li>A .htaccess file (apache servers) can be placed in the WebFM root (or sub-path) to secure file access. Webfm streams downloads and thus your browser doesn\'t require direct http access to the directories</li>
<li>Updating the menu cache by navigating to admin/build/menu may be necessary if upgrading from an earlier version of the module with different internal paths.</li>
<li>Translations of the module require revising the string array at the top of webfm.js.</li>
</ul>
<h2>Usage</h2>
<p>There are many ways to setup a file system hierarchy. The rules of any given system must be applied carefully if security of data is important.</p>
<p>The basic rules for users in a role with \'access webfm\' rights:</p>
<ul>
<li>The role root directory defines the domain and all subdirectories are accessible to the user.</li>
<li>The user cannot navigate above the role root directory.</li>
<li>Only files in the webfm_file table are accessible. Files uploaded by the user are owned by the user and are automatically in the database. Only module admins can view/operate on files not in the database.</li>
<li>The user has full control over files that he/she owns that stay within an accessible role root domain. File permissions can be locked down so that only the owner/admins can see or operate on a file. File permissions can be opened up so that anyone within the role can view or operate on the file.</li>
<li>Users with \'access webfm\' rights cannot create/delete/move/rename directories. Only module administrators (users with \'administer webfm\' permission or #1 user) can control the directory structure.</li>
</ul>
<p>Roles with \'access webfm\' rights can be subsets of other roles with \'access webfm\' rights or they can be exclusive. Users can be members of multiple roles and will consequently have a separate left-hand tree for each unique root directory (roles can even share the same root directory). It is difficult to foresee how diverse users of the module will choose to set up their systems but the following simple examples are typical arrangements. Both examples presume that the drupal file-system directory is set to \'files\', the WebFM module is installed and the \'WebFM root directory\' is set to \'webfm\'.</p>
<h3> Example 1</h3>
<p>The site requires 1 class of privileged users (A) to administer the file system and 2 classes of WebFM users (B & C) with access to file resources. Both roles will be able to upload files. Some WebFM users are members of both B & C while others are members of only one. Uploaded files are by default only accessible by the file owner and admins.</p>
<ul>
<li>A site administrator will create 3 the roles A, B and C. Role A will have the \'administer webfm\' permission set in .../admin/user/access. B & C will have the \'access webfm\' and the \'webfm upload\' permission set.</li>
<li>WebFM settings will now have a fieldset for roles B & C where the root directory for each role is set. The root of B is set to \'B\' which automatically creates the \'files/webfm/B\' directory. The root of C is set to \'C\' which creates the directory \'files/webfm/C\'. A user who is a member of only one of B or C will see a single left-hand directory tree that contains their domain. They will have no access to files within the other role domain. Users who are members of both B & C will have two left-hand directory trees and have the ability to move files they own or control between the two domains. Role A\'s root directory is the \'WebFM root directory\' and thus A users see only a single left-hand tree of the entire module file-sys.</li>
<li>In WebFM settings, the \'Default File Permissions\' are configured with all checkboxes unset. This combination of default file permissions means that files that are uploaded will initially only be viewable by the B or C user doing the upload (owner) and by A users. Individual file permissions are editable by the file owner or A user to permit other users to view/attach/modify the file. One consequence of granting the permission \'Role Full Access\' is that a non-admin user with a single domain could lose contact with their own file if a dual domain non-admin user moves it to the other domain.</li>
</ul>
<h3> Example 2</h3>
<p>The site requires 1 class of privileged users (A) to administer the file system and 2 classes of users (B & C) with access to file resources. C is determined to be a subset of B such that B can access it\'s own files as well as those of C. C will not be able to upload files to the browser but will only be able to view/download or attach files to nodes. B will be able to upload files.</p>
<ul>
<li>A site administrator will create 3 the roles A, B and C. Role A will have the \'administer webfm\' permission set in .../admin/user/access. B & C will have the \'access webfm\' permission set. B will also have the \'webfm upload\' permission set.</li>
<li>WebFM settings will now have a fieldset for roles B & C where the root directory for each role is set. First the root of B is set to \'B\' which automatically creates the \'files/webfm/B\' directory. Next the root of C is set to \'B/C\' which creates the directory \'files/webfm/B/C\'. Since C is a sub-dir of B, role B will have access to C but C will not be able to navigate above it\'s root to see B\'s files. The left-hand directory tree will appear different for B & C. B\'s tree will start at \'B\' and have a \'C\' sub-directory (and potentially other sub-directories as set up by A). C\'s tree is a subset of B\'s tree. Role A\'s root directory is the \'WebFM root directory\'.</li>
<li>In WebFM settings, the \'Default File Permissions\' are configured with \'Role View Access\' and \'Role Attach Access\' set. This combination of file permissions means that files that a B user uploads/moves into the C realm will by default be viewable by C and be attachable to nodes that C creates. A B file owner can manually modify the file permissions of each individual file to hide it or prevent it from being attached to content by a C user. Likewise the file permissions can be opened so that a C user can edit file attributes or move the file into another sub-directory of C.</li>
</ul>
<p>In the above examples the site administrator may simply create the roles/access rules and then let an A user configure WebFM for B & C.</p>
<h2>Uninstall</h2>
<ol>
<li>Disable the module on the /admin/build/modules page</li>
<li>Click on the uninstall tab and select the module for removal. This will automatically drop the webfm_file and webfm_attach tables as well as all configuration variables. <i><strong>NOTE:</strong></i> This action will permanently discard all attachment and metedata information and cannot be undone. Execute the first step only if you wish to restore WebFM later without loss of data.</li>
</ol>
<h2>Onunload event handling in template</h2>
<p>To explicitly destroy the event closures to minimize browser memory leaks an unload event needs to fire. Unfortunately the control of the body tag happens in the template. Add this function to template.php:</p>
<pre>
function phptemplate_unload() {
if(module_exists(\'webfm\')) {
$path = $_SERVER[\'REQUEST_URI\'];
if((strstr($path, \'webfm\')) ||
(strstr($path, \'node\') && strstr($path, \'edit\')))
print \' onunload="Webfm.unregisterAllEvents();"\';
}
}
}
</pre>
<p>Add the following inside the php tag of the body tag of page.tpl.php:
<pre>
print phptemplate_unload();
</pre></p>
', array(
'%file-sys' => url('admin/settings/file-system'),
));
return $output;
case 'admin/modules#description':
return t('Enable the Web File Manager.');
}
}
function webfm_link($type, $node = NULL, $teaser = FALSE) {
$links = array();
if ($teaser && $type == 'node' && isset($node->webfm_files) && user_access('view webfm attachments')) {
if ($num_files = count($node->webfm_files)) {
$links['webfm_attachments'] = array(
'title' => format_plural($num_files, '1 attachment', '@count attachments'),
'href' => "node/{$node->nid}",
'attributes' => array(
'title' => t('Read full article to view attachments.'),
),
'fragment' => 'attachments',
);
}
}
return $links;
}
function webfm_admin_settings_validate($form_id, $form_values) {
$valid_webfm_root = FALSE;
$webfm_root_dir_name = $form_values['webfm_root_dir'];
if (!empty($webfm_root_dir_name)) {
if (!preg_match('/^[0-9a-zA-Z]/', $webfm_root_dir_name)) {
form_set_error('webfm_root_dir' . $rid, t('The leading character of the webfm root directory name must be alphanumeric.'));
}
else {
if (preg_match('[\\.]', $webfm_root_dir_name)) {
form_set_error('webfm_root_dir' . $rid, t('The webfm root directory name is not valid.'));
}
else {
$webfm_root_dir = file_directory_path() . "/" . $webfm_root_dir_name;
$valid_webfm_root = file_check_directory($webfm_root_dir, FILE_CREATE_DIRECTORY, 'webfm_root_dir');
}
}
}
if ($form_values['webfm_max_resolution'] != '0') {
if (!preg_match('/^[0-9]+[xX][0-9]+$/', $form_values['webfm_max_resolution'])) {
form_set_error('webfm_max_resolution', t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction.'));
}
}
$exceed_max_msg = t('Your PHP settings limit the maximum file size per upload to %size MB.', array(
'%size' => file_upload_max_size(),
)) . '<br/>';
$more_info = t("Depending on your sever environment, these settings may be changed in the system-wide php.ini file, a php.ini file in your Drupal root directory, in your Drupal site's settings.php file, or in the .htaccess file in your Drupal root directory.");
$max_upload_size = file_upload_max_size() / (1024 * 1024);
foreach ($form_values['roles'] as $rid => $role) {
$uploadsize = $form_values['webfm_uploadsize_' . $rid];
$usersize = $form_values['webfm_usersize_' . $rid];
$role_root_dir_name = $form_values['root_dir_' . $rid];
if (!empty($role_root_dir_name)) {
if ($valid_webfm_root) {
if (!preg_match('/^[0-9a-zA-Z]/', $role_root_dir_name)) {
form_set_error('root_dir_' . $rid, t('The leading character of the %role root directory must be alphanumeric.', array(
'%role' => $role,
)));
}
else {
if (preg_match('[\\.]', $role_root_dir_name)) {
form_set_error('root_dir_' . $rid, t('The %role root directory name is not valid.', array(
'%role' => $role,
)));
}
else {
$role_root_dir = $webfm_root_dir . "/" . $role_root_dir_name;
file_check_directory($role_root_dir, FILE_CREATE_DIRECTORY, 'root_dir_' . $rid);
}
}
}
else {
form_set_error('root_dir_' . $rid, t('The WebFM root directory must be valid for the %role root directory name to be valid.', array(
'%role' => $role,
)));
}
}
if (!is_numeric($uploadsize) || $uploadsize <= 0) {
form_set_error('webfm_uploadsize_' . $rid, t('The %role file size limit must be a number and greater than zero.', array(
'%role' => $role,
)));
}
if (!is_numeric($usersize) || $usersize <= 0) {
form_set_error('webfm_usersize_' . $rid, t('The %role file size limit must be a number and greater than zero.', array(
'%role' => $role,
)));
}
if ($uploadsize > $max_upload_size) {
form_set_error('webfm_uploadsize_' . $rid, $exceed_max_msg . $more_info);
$more_info = '';
}
if ($uploadsize > $usersize) {
form_set_error('webfm_uploadsize_' . $rid, t('The %role maximum file size per upload is greater than the total file size allowed per user', array(
'%role' => $role,
)));
}
}
}
function webfm_admin_settings() {
global $user;
$modulepath = drupal_get_path('module', 'webfm');
$form['webfm_root_dir'] = array(
'#type' => 'textfield',
'#title' => t('WebFM root directory'),
'#default_value' => variable_get('webfm_root_dir', ''),
'#maxlength' => '100',
'#size' => '70',
'#description' => t('Root directory used to present the filebrowser user interface.
<br />This path is relative to "File system path" set in admin/settings/file-system.
<br />If this directory path is compound (ie: path/to/root) then the path must already
<br />exist for this setting to validate (ie: path/to).'),
);
$form['webfm_icon_dir'] = array(
'#type' => 'textfield',
'#title' => t('Icon directory'),
'#default_value' => variable_get('webfm_icon_dir', $modulepath . '/image/icon'),
'#maxlength' => '100',
'#size' => '70',
'#description' => t('Name of directory where file type icons are stored (relative to base url).'),
);
$form['webfm_max_resolution'] = array(
'#type' => 'textfield',
'#title' => t('Maximum resolution for uploaded images'),
'#default_value' => variable_get('webfm_max_resolution', 0),
'#size' => 15,
'#maxlength' => 10,
'#description' => t('The maximum allowed image size (e.g. 640x480). Set to 0 for no restriction.'),
'#field_suffix' => '<kbd>' . t('WIDTHxHEIGHT') . '</kbd>',
);
$form['webfm_date_format'] = array(
'#type' => 'radios',
'#title' => t('Date Format'),
'#default_value' => variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY),
'#options' => array(
WEBFM_DATE_FORMAT_DAY => t('dd/mm/yy'),
WEBFM_DATE_FORMAT_MONTH => t('mm/dd/yy'),
),
'#description' => t('Set the order of day/month in date fields.'),
);
$form['webfm_display_title'] = array(
'#type' => 'checkbox',
'#title' => t('Display metadata title'),
'#default_value' => variable_get('webfm_display_title', ''),
'#description' => t('Check this box to display the metadata title in the browser instead of the filename.
<br />If a metadata title doesn\'t exist, the filename is used and rename functions normally.
<br />If metadata title is used, renaming is available inside the metadata editor.'),
);
$form['file_perm'] = array(
'#type' => 'fieldset',
'#title' => t('Default File Permissions'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('Default permissions applied to a file when inserted into the database.
<br />If all boxes are unchecked only the file owner and administrators will have
<br />access to the file via the filebrowser. File owners and admins can change
<br />these settings for each individual file within the filebrowser UI.'),
);
$form['file_perm']['webfm_file_perm_role'] = array(
'#type' => 'checkbox',
'#title' => t('Role View Access'),
'#default_value' => variable_get('webfm_file_perm_role', ''),
'#description' => t('File is viewable/downloadable in the filebrowser by role.'),
);
$form['file_perm']['webfm_file_perm_mod'] = array(
'#type' => 'checkbox',
'#title' => t('Role Full Access'),
'#default_value' => variable_get('webfm_file_perm_mod', ''),
'#description' => t('Roles that can access this file via the filebrowser have the same access rights as the
<br />file owner except for the right to change the file permissions.'),
);
$form['file_perm']['webfm_file_perm_attach'] = array(
'#type' => 'checkbox',
'#title' => t('Role Attach Access'),
'#default_value' => variable_get('webfm_file_perm_attach', ''),
'#description' => t('Roles that can access this file via the filebrowser have the right to attach it to content.'),
);
$form['file_perm']['webfm_file_public'] = array(
'#type' => 'checkbox',
'#title' => t('Public Access'),
'#default_value' => variable_get('webfm_file_public', ''),
'#description' => t('File is downloadable anonymously via webfm_send.'),
);
$roles = user_roles(0, 'access webfm');
$form['roles'] = array(
'#type' => 'value',
'#value' => $roles,
);
webfm_get_extensions_regex(WEBFM_FLUSH);
foreach ($roles as $rid => $role) {
$form["settings_role_" . $rid] = array(
'#type' => 'fieldset',
'#title' => t('Settings for @role role', array(
'@role' => $role,
)),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form["settings_role_" . $rid]["root_dir_" . $rid] = array(
'#type' => 'textfield',
'#title' => t('Role Root directory'),
'#default_value' => variable_get("root_dir_" . $rid, ''),
'#maxlength' => '100',
'#size' => '70',
'#description' => t('Root directory for this role.
<br />This path is relative to "WebFM Root directory" set above.
<br />If this directory path is compound then the path must already exist for this
<br />setting to validate.'),
);
$form["settings_role_" . $rid]["webfm_extensions_" . $rid] = array(
'#type' => 'textfield',
'#title' => t('Permitted file extensions'),
'#default_value' => variable_get("webfm_extensions_" . $rid, "jpg jpeg gif png txt html htm doc xls pdf ppt pps dwg zip gz"),
'#maxlength' => 255,
'#description' => t('Extensions that users in this role can upload. Separate extensions with a space
<br />and do not include the leading dot.'),
);
$form["settings_role_" . $rid]["webfm_uploadsize_" . $rid] = array(
'#type' => 'textfield',
'#title' => t('Maximum file size per upload'),
'#default_value' => variable_get("webfm_uploadsize_" . $rid, 4),
'#size' => 5,
'#maxlength' => 5,
'#description' => t('The maximum size of a file a user can upload (in megabytes).
<br />Cannot exceed %size limit set in php.ini.', array(
'%size' => format_size(file_upload_max_size()),
)),
);
$form["settings_role_" . $rid]["webfm_usersize_" . $rid] = array(
'#type' => 'textfield',
'#title' => t('Total file size per user'),
'#default_value' => variable_get("webfm_usersize_" . $rid, 200),
'#size' => 5,
'#maxlength' => 5,
'#description' => t('The maximum size of all files a user can have on the site (in megabytes).'),
);
}
$form['attach'] = array(
'#type' => 'fieldset',
'#title' => t('WebFM attachments'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['attach']['webfm_attach_body'] = array(
'#type' => 'checkbox',
'#title' => t('Append file links to Node Body'),
'#default_value' => variable_get('webfm_attach_body', ''),
'#description' => t('Check this box to append file attachments table to the node body.
<br />This setting does not affect the attachment block.'),
);
$form['attach']['webfm_attach_new_window'] = array(
'#type' => 'checkbox',
'#title' => t('Open attachments in a new browser window'),
'#default_value' => variable_get('webfm_attach_new_window', ''),
);
$form['attach']['attrib'] = array(
'#type' => 'fieldset',
'#title' => t('Attachment List Properties'),
);
$form['attach']['attrib']['webfm_attach_desc'] = array(
'#type' => 'checkbox',
'#title' => t('Include file description metadata'),
'#default_value' => variable_get('webfm_attach_desc', ''),
'#description' => t('Check this box to add file description metadata beneath the attachment title.'),
);
$form['attach']['attrib']['webfm_attach_date'] = array(
'#type' => 'checkbox',
'#title' => t('Enable file date column'),
'#default_value' => variable_get('webfm_attach_date', ''),
'#description' => t('Check this box to add a create date column to the attachment table.'),
);
$form['attach']['attrib']['webfm_attach_size'] = array(
'#type' => 'checkbox',
'#title' => t('Enable file size column'),
'#default_value' => variable_get('webfm_attach_size', ''),
'#description' => t('Check this box to add a file size column to the attachment table.'),
);
if ($user->uid == 1) {
$form['ie'] = array(
'#type' => 'fieldset',
'#title' => t('IE Drag-and-Drop Normalization'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('number of pixels to offset drag objects from cursor position in IE browser.<br />This quantity is usually related to relative positioning used by the css.'),
);
$form['ie']['webfm_ie_dd_list_offset'] = array(
'#type' => 'textfield',
'#title' => t('IE drag and drop x-axis offset for right hand listing draggables'),
'#default_value' => variable_get('webfm_ie_dd_list_offset', '-190'),
'#maxlength' => '10',
'#size' => '10',
);
$form['ie']['webfm_ie_dd_tree_offset'] = array(
'#type' => 'textfield',
'#title' => t('IE drag and drop x-axis offset for directory tree draggables'),
'#default_value' => variable_get('webfm_ie_dd_tree_offset', '-34'),
'#maxlength' => '10',
'#size' => '10',
);
$form['debug'] = array(
'#type' => 'fieldset',
'#title' => t('WebFM debug'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['debug']['webfm_debug'] = array(
'#type' => 'checkbox',
'#title' => t('WebFM javascript debug'),
'#default_value' => variable_get('webfm_debug', ''),
'#description' => t('Check this box for javascript debug messaging.'),
);
$form['debug']['webfm_cron'] = array(
'#type' => 'checkbox',
'#title' => t('WebFM cron'),
'#default_value' => variable_get('webfm_cron', ''),
'#description' => t('Check this box to enable cleanup of orphaned file records in the database.
<br />NOTE: Use with caution - behaviour is to delete all file records without a
<br />valid file path. Manually renaming a WebFM directory (ie: via OS shell)
<br />and then running cron will delete all webfm_file table entries for that
<br />directory and it\'s sub-directories.'),
);
}
return system_settings_form($form);
}
function webfm_perm() {
return array(
'access webfm',
'view webfm attachments',
'administer webfm',
'webfm upload',
);
}
function webfm_menu($maycache) {
$items = array();
if ($maycache) {
$items[] = array(
'title' => t('Web File Manager'),
'path' => 'webfm',
'access' => user_access('access webfm'),
'callback' => 'webfm_main',
);
$items[] = array(
'title' => t('Web File Manager'),
'path' => 'webfm_js',
'access' => user_access('access webfm'),
'callback' => 'webfm_ajax',
'type' => MENU_CALLBACK,
);
$items[] = array(
'title' => t('Web File Manager'),
'path' => 'webfm/upload',
'access' => user_access('access webfm'),
'callback' => 'webfm_upload',
'type' => MENU_CALLBACK,
);
$items[] = array(
'title' => t('File Not Found'),
'path' => 'webfm_send',
'access' => true,
'callback' => 'webfm_send_file',
'type' => MENU_CALLBACK,
);
$items[] = array(
'path' => 'admin/settings/webfm',
'title' => t('Web File Manager Settings'),
'description' => t('Configure WebFM.'),
'callback' => 'drupal_get_form',
'callback arguments' => array(
'webfm_admin_settings',
),
'access' => user_access('administer webfm'),
'type' => MENU_NORMAL_ITEM,
);
}
return $items;
}
function webfm_block($op = 'list', $delta = 0) {
if ($op == 'list') {
$blocks[0]['info'] = t('WebFM File Attachments');
return $blocks;
}
else {
if ($op == 'view' && user_access('access content') && user_access('view webfm attachments')) {
$block['content'] = webfm_attach_box();
$block['subject'] = t('Attachments');
return $block;
}
}
}
function webfm_cron() {
if (variable_get('webfm_cron', '')) {
$result = db_query('SELECT fpath, fid FROM {webfm_file}');
while ($f = db_fetch_array($result)) {
if (!is_file($f['fpath'])) {
_webfm_dbdelete_file_fid($f['fid']);
}
}
}
}
function webfm_nodeapi(&$node, $op, $teaser) {
global $user;
switch ($op) {
case 'load':
if (variable_get("wfm_attach_{$node->type}", 1) == 1 && user_access('view webfm attachments')) {
$output['webfm_files'] = webfm_get_attachments($node->nid);
}
return $output;
break;
case 'view':
if (variable_get('webfm_attach_body', '')) {
if (!user_access('access webfm') && variable_get("wfm_attach_{$node->type}", 1) == 1 && user_access('view webfm attachments')) {
$node->webfm_files = webfm_get_attachments($node->nid);
}
if (is_array($node->webfm_files)) {
if (count($node->webfm_files) && !$teaser) {
$show_files = $node->webfm_files;
}
}
elseif ($_POST['attachlist'] && user_access('view webfm attachments')) {
$show_files = webfm_get_temp_attachments($_POST['attachlist']);
}
if ($show_files) {
$node->content['webfm_attachments'] = array(
'#value' => theme('webfm_attachments', $show_files),
'#weight' => 10,
);
drupal_add_css(drupal_get_path('module', 'webfm') . '/css/webfm.css');
}
}
break;
case 'validate':
$modulepath = drupal_get_path('module', 'webfm');
drupal_add_js($modulepath . '/js/webfm.js');
drupal_add_css($modulepath . '/css/webfm.css');
if (is_null($inline_js)) {
$clean_url = variable_get('clean_url', 0);
$clean = $clean_url == 0 || $clean_url == '0' ? FALSE : TRUE;
$inline_js = webfm_inline_js($base_url, $clean, $user->uid);
}
break;
case 'insert':
unset($node->attachlist);
if ($_POST['attachlist']) {
$files = explode(',', $_POST['attachlist']);
$i = 0;
foreach ($files as $fid) {
if ($fid) {
webfm_dbinsert_attach($node->nid, $fid, $i++);
}
}
}
break;
case 'update':
if (user_access('access webfm')) {
$files = explode(',', $_POST['attachlist']);
webfm_dbupdate_attach($node->nid, $files);
}
break;
case 'delete':
webfm_dbdelete_attachments($node->nid);
break;
}
}
function webfm_form_alter($form_id, &$form) {
global $base_url;
global $user;
if ($user->uid == 1 || user_access('administer webfm') || user_access('access webfm')) {
$access = TRUE;
}
else {
$access = FALSE;
}
if ($form_id == 'node_type_form' && $access) {
$form['workflow']['webfm_attach'] = array(
'#type' => 'radios',
'#title' => t('WebFM Attachments'),
'#default_value' => variable_get('webfm_attach_' . $form['#node_type']->type, 0),
'#options' => array(
0 => t('Disabled'),
1 => t('Enabled'),
),
'#description' => t('Should this content type allow upload & file attachment via WebFM?'),
);
}
if (isset($form['type'])) {
$node = $form['#node'];
if ($access && $form['type']['#value'] . '_node_form' == $form_id && variable_get('webfm_attach_' . $node->type, 0)) {
$modulepath = drupal_get_path('module', 'webfm');
drupal_add_js($modulepath . '/js/webfm.js');
drupal_add_css($modulepath . '/css/webfm.css');
if (is_null($inline_js)) {
$clean_url = variable_get('clean_url', 0);
$clean = $clean_url == 0 || $clean_url == '0' ? FALSE : TRUE;
$inline_js = webfm_inline_js($base_url, $clean, $user->uid);
}
$form['webfm-attach']['#theme'] = 'webfm_upload_form';
$form['webfm-attach']['attach'] = array(
'#type' => 'fieldset',
'#title' => t('WebFM Attachments'),
'#description' => t('Drag attachments to set order.<br />Changes made to the attachments are not permanent until you save this post.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#weight' => 29,
);
$form['webfm-attach']['attach']['attachedfiles'] = array(
'#prefix' => '<div id="webfm-attach">',
'#suffix' => '</div>',
);
$form['webfm-attach']['attach']['attachedfiles'] += webfm_attach_attached_form($node);
$form['webfm-attach']['attach']['browser'] = array(
'#type' => 'fieldset',
'#title' => t('File Browser'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
if ($user->uid == 1 || user_access('administer webfm')) {
$form['webfm-attach']['attach']['browser'] += webfm_links();
}
if ($user->uid == 1 || user_access('administer webfm') || user_access('webfm upload')) {
$form['webfm-attach']['attach']['browser']['wrapper'] = array(
'#type' => 'fieldset',
'#title' => t('File Upload'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('Uploaded file will be saved to the current directory.'),
'#prefix' => '<div id="webfm-inline">',
'#suffix' => '</div>',
);
$form['webfm-attach']['attach']['browser']['wrapper']['wrapper'] = array(
'#prefix' => '<div id="wfmatt-wrapper">',
'#suffix' => '</div>',
);
$form['webfm-attach']['attach']['browser']['wrapper']['wrapper'] += webfm_upload_form('webfm/upload');
$form['#attributes']['enctype'] = 'multipart/form-data';
}
else {
$form['webfm-attach']['attach']['browser']['wrapper'] = array(
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#prefix' => '<div id="webfm-inline">',
'#suffix' => '</div>',
);
}
}
}
}
function webfm_links() {
$form['#theme'] = 'webfm_attach_attached_form';
$debug_link = drupal_to_js(variable_get('webfm_debug', '')) ? t('[<a href=# id="webfm-debug-link">debug</a>]') : '';
$settings_link = t('[<a href="@link">settings...</a>]', array(
'@link' => url("admin/settings/webfm"),
));
$help_link = module_hook('help', 'page') ? t('[<a href="@link">more help...</a>]', array(
'@link' => url("admin/help/webfm"),
)) : '';
$output = $debug_link . $settings_link . $help_link;
if ($output) {
$form['links'] = array(
'#prefix' => '<div class="more-help-link">',
'#suffix' => '</div>',
);
$form['links']['content'] = array(
'#type' => 'markup',
'#value' => $output,
);
}
return $form;
}
function webfm_attach_attached_form($node) {
$form['#theme'] = 'webfm_attach_attached_form';
$form['new']['attachlist'] = array(
'#type' => 'hidden',
'#default_value' => '',
);
if ($_POST['attachlist']) {
$form['new']['attachlist']['#default_value'] = $_POST['attachlist'];
}
return $form;
}
function theme_webfm_attach_attached_form($form) {
$output = drupal_render($form);
return $output;
}
function webfm_attach_box() {
if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
$node = node_load(arg(1));
}
$files = webfm_get_attachments($node->nid);
return theme('webfm_attachments', $files);
}
function theme_webfm_attachments($files) {
global $base_url;
$header = array(
t('Attachment'),
);
if ($enable_date = variable_get('webfm_attach_date', '')) {
array_push($header, t('Date'));
}
if ($enable_size = variable_get('webfm_attach_size', '')) {
array_push($header, t('Size'));
}
$rows = array();
foreach ($files as $file) {
$icon_path = $base_url . '/' . variable_get('webfm_icon_dir', '') . '/' . _webfm_get_icon($file->e);
$description = '';
if (variable_get('webfm_attach_desc', '') && !empty($file->fdesc)) {
$description = '<div class="att-fdesc">' . $file->fdesc . '</div>';
}
$filename = $file->ftitle ? $file->ftitle : $file->n;
if (variable_get('webfm_attach_new_window', '')) {
$href = array(
'data' => l('<img src="' . $icon_path . '" alt="[file]" title="Download ' . $filename . '"/> ', 'webfm_send/' . $file->id . '/1', array(
'title' => 'Download ' . $filename,
'target' => '_blank',
), '', '', '', TRUE) . l($filename, 'webfm_send/' . $file->id, array(
'title' => 'Open ' . $filename,
'target' => '_blank',
)) . $description,
'class' => 'att-title',
);
}
else {
$href = array(
'data' => l('<img src="' . $icon_path . '" alt="[file]" title="Download ' . $filename . '"/> ', 'webfm_send/' . $file->id . '/1', array(
'title' => 'Download ' . $filename,
), '', '', '', TRUE) . l($filename, 'webfm_send/' . $file->id, array(
'title' => 'Open ' . $filename,
)) . $description,
'class' => 'att-title',
);
}
$row = array();
array_push($row, $href);
if ($enable_date) {
$time = $file->fcreatedate ? date(webfm_get_date_format(), $file->fcreatedate) : date(webfm_get_date_format(), @filemtime($file->p . '/' . $file->n));
array_push($row, array(
'data' => $time,
'class' => 'att-time',
));
}
if ($enable_size) {
array_push($row, array(
'data' => format_size($file->s),
'class' => 'att-size',
));
}
array_push($rows, $row);
}
if (count($rows)) {
return theme('table', $header, $rows, array(
'id' => 'webfm-attach-list',
));
}
}
function _webfm_get_icon($ext) {
switch (strtolower($ext)) {
case 'image/gif':
case 'image/png':
case 'image/jpg':
case 'image/jpeg':
case 'image/bmp':
case 'image/tiff':
case 'jpg':
case 'gif':
case 'png':
case 'jpeg':
case 'bmp':
case 'tiff':
$icon = 'i.gif';
break;
case 'video/mpeg':
case 'video/x-msvideo':
case 'avi':
$icon = 'avi.gif';
break;
case 'video/quicktime':
case 'mov':
$icon = 'qt.gif';
break;
case 'audio/mpeg':
case 'mpeg':
case 'mp3':
$icon = 'mp3.gif';
break;
case 'application/pdf':
case 'pdf':
$icon = 'pdf.gif';
break;
case 'application/zip':
case 'application/x-zip':
case 'application/x-gzip':
case 'zip':
$icon = 'zip.gif';
break;
case 'application/msword':
case 'doc':
case 'odt':
$icon = 'doc.gif';
break;
case 'application/vnd.ms-excel':
case 'xls':
case 'ods':
$icon = 'xls.gif';
break;
case 'application/vnd.ms-powerpoint':
case 'pps':
case 'ppt':
case 'odp':
$icon = 'pps.gif';
break;
default:
$icon = 'f.gif';
break;
}
return $icon;
}
function webfm_roles_alter($rid, $name, $op) {
if ($op == t('Save role')) {
drupal_set_message(t('The webfm role has been renamed.'));
}
else {
if ($op == t('Delete role')) {
drupal_set_message(t('The webfm role has been deleted.'));
}
else {
if ($op == t('Add role')) {
drupal_set_message(t('The webfm role has been added.'));
}
}
}
}
function _webfm_image(&$file) {
$info = image_get_info($file->filepath);
if ($info) {
$res = variable_get('webfm_max_resolution', 0);
if ($res != 0) {
list($width, $height) = explode('x', strtolower($res));
if ($info['width'] > $width || $info['height'] > $height) {
if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) {
drupal_set_message(t('The image was resized to fit within the maximum allowed resolution of %resolution pixels.', array(
'%resolution' => variable_get('webfm_max_resolution', 0),
)));
clearstatcache();
$info = image_get_info($file->filepath);
$file->filesize = $info['file_size'];
}
else {
drupal_set_message(t('The image is too large.'));
}
}
}
}
}
function webfm_upload() {
global $user;
$json_data = array();
$fid = '';
if ($_POST['webfmuploadpath']) {
$root_dir = $user->uid == 1 || user_access('administer webfm') ? file_directory_path() : file_directory_path() . webfm_get_root_path();
$dest = $root_dir . $_POST['webfmuploadpath'];
if (($file = file_check_upload('webfm_upload')) != FALSE) {
_webfm_image($file);
if (webfm_upload_validate($file, $err) === TRUE) {
$upload_path = $dest . '/' . $file->filename;
if (is_file($upload_path)) {
$file->in_db = ($webfm_file_row = webfm_get_file_record('', $upload_path)) ? TRUE : FALSE;
$file->dest = $dest;
$_SESSION['temp_upload'] = $file;
$json_data['file'] = $file->filename;
if ($file->in_db) {
if ($webfm_file_row->uid == $user->uid || user_access('administer webfm')) {
$json_data['html'] = webfm_reload_upload('webfm/upload', webfm_version_form($file->filename));
}
else {
drupal_set_message(t('Permission denied to overwrite existing file'), error);
}
}
else {
$msg = '';
if (($fid = webfm_version_upload(WEBFM_REPLACE_RENAME, $msg)) !== FALSE) {
drupal_set_message(t('Upload Success'));
}
else {
drupal_set_message(t('Insertion into database fail'), error);
}
}
}
else {
if (file_move($file, $dest)) {
if (($fid = webfm_dbinsert_file($file, $err)) !== FALSE) {
drupal_set_message(t('Upload Success'));
}
else {
file_delete($file->filepath);
drupal_set_message(t('Insertion into database fail'), error);
}
}
else {
drupal_set_message(t('file_move to %path failed', array(
'%path' => $dest,
)), error);
}
}
}
else {
drupal_set_message(t('file %s is not valid for upload', array(
'%s' => $file->filename,
)), error);
}
}
else {
if (!isset($_FILES['files']) || $_FILES['files']['name']['webfm_upload'] == '') {
drupal_set_message(t('Please click "Browse" and select a file to upload before clicking the upload button.'), error);
}
}
}
else {
drupal_set_message(t('Invalid upload path'), error);
}
if (!isset($json_data['html'])) {
$json_data['html'] = webfm_reload_upload('webfm/upload');
}
if ($fid) {
$json_data['fid'] = $fid;
}
print drupal_to_js(array(
'status' => TRUE,
'data' => $json_data,
));
exit;
}
function webfm_reload_upload($url, $confirm_form = '') {
$form = array();
if ($confirm_form) {
array_push($form, $confirm_form);
}
array_push($form, webfm_upload_form($url));
$form = form_builder('upload_js', $form);
$output = theme('status_messages') . drupal_render($form);
return $output;
}
function webfm_ajax() {
global $user;
if ($user->uid == 1 || user_access('administer webfm')) {
$webfm_perm = WEBFM_ADMIN;
}
else {
if (user_access('access webfm')) {
$webfm_perm = WEBFM_USER;
}
else {
exit;
}
}
$webfm_root_path = webfm_get_root_path();
if ($webfm_root_path == NULL) {
webfm_json(array(
'status' => FALSE,
'err' => t('WebFM root not set'),
));
exit;
}
$root_dir = $webfm_perm == WEBFM_ADMIN ? file_directory_path() : file_directory_path() . $webfm_root_path;
if (isset($_POST["action"])) {
switch (trim(strtolower($_POST["action"]))) {
case "readtrees":
$trees = array();
$err = '';
if ($webfm_perm == WEBFM_ADMIN) {
unset($_SESSION['tree_' . $webfm_root_path]);
$trees[0] = webfm_tree($root_dir, $webfm_root_path);
}
else {
$webfm_roots = webfm_get_root_dirs(TRUE);
if (count($webfm_roots)) {
foreach ($webfm_roots as $key => $sub_root) {
if (!empty($sub_root)) {
$sub_root_path = $root_dir . $sub_root;
if (is_dir($sub_root_path)) {
$current = $sub_root;
unset($_SESSION['tree_' . $current]);
$trees[$key] = webfm_tree($root_dir, $current);
}
else {
$err .= ' ' . $sub_root_path . t(' root dir not found.');
}
}
else {
$err .= t(' Root directory not set for @role role ', array(
'@role' => $webfm_access_roles[$key],
));
}
}
}
else {
$err = t('No root directory set in WebFM settings for this role');
}
}
if (count($trees)) {
webfm_json(array(
'status' => TRUE,
'tree' => $trees,
'current' => $webfm_root_path,
'admin' => $webfm_perm == WEBFM_ADMIN,
'err' => $err,
));
}
else {
$err .= t(' No trees found.');
webfm_json(array(
'status' => FALSE,
'err' => $err,
));
}
exit;
break;
case "readtree":
$tree = '';
unset($current);
if ($webfm_perm == WEBFM_ADMIN) {
$current = $webfm_root_path;
}
else {
if (isset($_POST["param0"])) {
$webfm_roots = webfm_get_root_dirs();
$root_role = trim(rawurldecode($_POST["param0"]));
if (($root = variable_get("root_dir_" . $root_role, '')) && array_key_exists($root_role, $webfm_roots)) {
$current = "/" . $root;
}
}
}
if (!isset($current)) {
webfm_json(array(
'status' => FALSE,
'data' => t('unknown tree'),
));
exit;
break;
}
if (isset($_POST["param1"])) {
unset($_SESSION['tree_' . $current]);
}
if (!is_dir($root_dir . $current)) {
webfm_json(array(
'status' => FALSE,
'data' => t('unknown role'),
));
}
else {
$tree = webfm_tree($root_dir, $current);
webfm_json(array(
'status' => isset($tree) ? TRUE : FALSE,
'tree' => $tree,
'current' => $current,
'admin' => $webfm_perm == WEBFM_ADMIN,
));
}
exit;
break;
case "read":
if (isset($_POST["param0"])) {
$param0 = trim(rawurldecode($_POST["param0"]));
if (ereg('\\.\\.', $param0)) {
webfm_json(array(
'status' => FALSE,
'data' => t('illegal read dir'),
));
exit;
}
$perm_flag = FALSE;
if ($webfm_perm == WEBFM_ADMIN) {
if (webfm_check_path($param0, $webfm_root_path)) {
$perm_flag = TRUE;
}
}
else {
$webfm_roots = webfm_get_root_dirs();
foreach ($webfm_roots as $key => $sub_root) {
if ($sub_root && webfm_check_path($param0, $sub_root)) {
$perm_flag = TRUE;
break;
}
}
}
if ($perm_flag) {
if (!is_dir($root_dir . $param0)) {
webfm_json(array(
'status' => FALSE,
'data' => $root_dir . $param0 . t(' path does not exist - refresh required'),
));
exit;
}
$dirlist = new webfm_build_dir_list($root_dir, $param0, $webfm_perm);
if ($dirlist
->get_breadcrumb()) {
webfm_json(array(
'status' => TRUE,
'current' => $param0,
'bcrumb' => $dirlist
->get_breadcrumb(),
'dirs' => $dirlist
->get_dir_listing(),
'files' => $dirlist
->get_file_listing(),
'user' => $user->uid,
'admin' => $webfm_perm == WEBFM_ADMIN,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('invalid dir'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('forbidden dir'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "delete":
if (isset($_POST["param0"])) {
$param0 = trim(rawurldecode($_POST["param0"]));
if ($param0 && !ereg('\\.\\.', $param0)) {
$source = $root_dir . $param0;
if (is_dir($source)) {
if ($webfm_perm == WEBFM_ADMIN) {
$err_arr[] = array();
$ret = webfm_delete_dir_recur($source, TRUE, $err_arr);
webfm_json(array(
'status' => $ret,
'data' => $err_arr,
));
exit;
break;
}
}
else {
if (is_file($source)) {
$permit = FALSE;
$file = webfm_get_file_record('', $source);
if ($webfm_perm == WEBFM_ADMIN) {
$permit = TRUE;
}
else {
if ($file) {
if ($user->uid == $file->uid || webfm_file_mod_access($file)) {
$permit = TRUE;
}
}
}
if ($permit) {
$error = "";
$ret = TRUE;
if (@unlink($source)) {
if ($file && !webfm_dbdelete_file($file->fid)) {
$error = t('webfm_dbdelete_file() fail for ') . $source;
$ret = FALSE;
}
}
else {
if (file_exists($source)) {
$error = $source . t(' could not be deleted');
$ret = FALSE;
}
}
webfm_json(array(
'status' => $ret,
'data' => $error,
));
exit;
break;
}
}
}
}
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "mkdir":
if ($webfm_perm == WEBFM_ADMIN) {
if (isset($_POST["param0"])) {
$source = $root_dir . trim(rawurldecode($_POST["param0"]));
$dest = t("New_Folder");
$err_arr[] = array();
if (($ret = webfm_mkdir($source, $dest, TRUE, $err_arr)) !== FALSE) {
$ret = ltrim($ret, $root_dir);
webfm_json(array(
'status' => TRUE,
'data' => $ret,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => $err_arr,
));
}
if ($ret) {
unset($_SESSION['tree_' . $webfm_root_path]);
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
}
exit;
break;
case "move":
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$source = $root_dir . trim(rawurldecode($_POST["param0"]));
$dest = $root_dir . trim(rawurldecode($_POST["param1"]));
if (is_dir($source) && $webfm_perm != WEBFM_ADMIN) {
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
exit;
break;
}
if ($source != $dest) {
if (!ereg('\\.\\.', $dest)) {
$err_arr[] = array();
$ret = webfm_move($source, $dest, $webfm_perm == WEBFM_USER ? $user->uid : 1, $err_arr);
webfm_json(array(
'status' => $ret,
'data' => $err_arr,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('illegal destination path'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('move operation not permitted'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "rename":
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$source = $root_dir . trim(rawurldecode($_POST["param0"]));
$dest = $root_dir . trim(rawurldecode($_POST["param1"]));
if (!ereg('\\.\\.', $dest) && dirname(rawurldecode($_POST["param0"])) == dirname(rawurldecode($_POST["param1"]))) {
$err_arr[] = array();
$ret = webfm_rename($source, $dest, $webfm_perm == WEBFM_USER ? $user->uid : 1, $err_arr);
webfm_json(array(
'status' => $ret,
'data' => $err_arr,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('illegal name'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "search":
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$source = trim(rawurldecode($_POST["param0"]));
$searchpattern = trim(rawurldecode($_POST["param1"]));
if ($searchpattern != "") {
$regexpsearch = '';
@clearstatcache();
$search = new webfm_searchFiles($root_dir, $source, $searchpattern, $regexpsearch, $webfm_perm == WEBFM_USER ? $user->uid : 1);
webfm_json(array(
'files' => $search
->get_files(),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "getmeta":
if (isset($_POST["param0"])) {
$fid = rawurldecode($_POST["param0"]);
if (($file = webfm_get_file_record($fid)) !== FALSE) {
if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file) || webfm_file_view_access($file)) {
$meta = array();
if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file)) {
$meta['id'] = $file->fid;
if ($webfm_perm == WEBFM_ADMIN) {
$meta['u'] = $file->uid;
}
}
$query = 'SELECT name FROM {users} WHERE uid = %d';
$meta['un'] = db_result(db_query($query, $file->uid));
$meta['n'] = strrev(substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/')));
$meta['t'] = $file->ftitle;
$meta['d'] = $file->fdesc;
$meta['l'] = $file->flang;
$meta['p'] = $file->fpublisher;
$meta['f'] = $file->fformat;
$meta['c'] = $file->dl_cnt;
if ($i = @getimagesize($file->fpath)) {
if ($i[0] != 0 && $i[1] != 0) {
$meta['i'] = (int) $i[2];
$meta['w'] = (int) $i[0];
$meta['h'] = (int) $i[1];
}
}
if ($file->perm & WEBFM_FILE_ACCESS_PUBLIC_VIEW) {
global $base_url;
$meta['lk'] = '<a href="' . $base_url . '/webfm_send/' . $file->fid . '">' . $meta['n'] . '</a>';
}
webfm_json(array(
'status' => TRUE,
'data' => $meta,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('file record not found'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "putmeta":
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$ret = webfm_putmeta(rawurldecode($_POST["param0"]), rawurldecode($_POST["param1"]), $webfm_perm == WEBFM_ADMIN ? 1 : $user->uid, $err);
webfm_json(array(
'status' => $ret,
'data' => $err,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "getperm":
if (isset($_POST["param0"])) {
$fid = rawurldecode($_POST["param0"]);
if (($file = webfm_get_file_record($fid)) !== FALSE) {
if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file)) {
$perm = array();
$perm['id'] = $file->fid;
$perm['u'] = $file->uid;
$perm['n'] = strrev(substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/')));
$perm['p'] = $file->perm;
webfm_json(array(
'status' => TRUE,
'data' => $perm,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('file record not found'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "putperm":
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$fid = rawurldecode($_POST["param0"]);
if (($file = webfm_get_file_record($fid)) !== FALSE) {
if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file)) {
$perm = array();
$msg = '';
$perm['perm'] = (int) rawurldecode($_POST["param1"]);
$status = FALSE;
if ($perm['perm'] >= 0 && $perm['perm'] <= WEBFM_MAX_FILE_ACCESS) {
if (webfm_dbupdate_file($fid, '', $perm)) {
$msg = t('Permissions saved');
$status = TRUE;
}
else {
$msg = t('webfm_dbupdate_file() fail');
}
}
else {
$msg = t('invalid permission');
}
}
else {
$msg = t('permission denied');
}
}
else {
$msg = t('file record not found');
}
}
else {
$msg = t('insufficient params');
}
webfm_json(array(
'status' => $status,
'data' => $perm,
'msg' => $msg,
));
exit;
break;
case "attach":
global $node;
if (isset($_POST["param0"])) {
if (isset($_POST["param1"])) {
$fids = trim(strtolower(rawurldecode($_POST["param1"])));
webfm_json(array(
'status' => TRUE,
'data' => webfm_get_temp_attachments($fids),
'admin' => 'attach',
));
exit;
break;
}
$node_str = trim(strtolower(rawurldecode($_POST["param0"])));
if (($node_num = strstr($node_str, 'node/')) !== FALSE) {
$node_arr = explode("/", $node_num);
webfm_json(array(
'status' => TRUE,
'data' => webfm_get_attachments($node_arr[1]),
'admin' => 'attach',
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('illegal path'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "attachfile":
if (isset($_POST["param0"])) {
$fid = rawurldecode($_POST["param0"]);
if (($_file = webfm_get_file_record($fid)) !== FALSE) {
if ($webfm_perm == WEBFM_ADMIN || $user->uid == $_file->uid || webfm_file_mod_access($_file) || webfm_file_att_access($_file)) {
$file = new webfm_fdesc($_file);
if ($file->result != FALSE) {
webfm_json(array(
'status' => TRUE,
'data' => $file,
'admin' => 'attach',
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('file ') . $fid . t(' path not found'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('invalid permission'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('file ') . $fid . t(' record not found'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
exit;
break;
case "insert":
if ($webfm_perm == WEBFM_ADMIN) {
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$source = $root_dir . trim(rawurldecode($_POST["param0"]));
$err_arr[] = array();
$result = FALSE;
switch (trim(rawurldecode($_POST["param1"]))) {
case "file":
$ret = webfm_insert_file($source, $err_arr);
$result = new stdClass();
$result->cnt = 0;
$result->errcnt = 0;
$result->err = '';
if (!$ret) {
$result->errcnt = 1;
$result->err = $err_arr;
webfm_json(array(
'status' => FALSE,
'data' => $result,
));
}
else {
$result->cnt = 1;
webfm_json(array(
'status' => TRUE,
'data' => $result,
));
}
break;
case "dir":
$result = webfm_insert_dir($source, FALSE, $err_arr);
if ($result->errcnt) {
$result->err = $err_arr;
}
webfm_json(array(
'status' => $result->cnt > 0,
'data' => $result,
));
break;
case "recur":
$result = webfm_insert_dir($source, TRUE, $err_arr);
if ($result->errcnt) {
$result->err = $err_arr;
}
webfm_json(array(
'status' => $result->cnt > 0,
'data' => $result,
));
break;
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
}
exit;
break;
case "dbrem":
if ($webfm_perm == WEBFM_ADMIN) {
if (isset($_POST["param0"])) {
if ($ret = trim(rawurldecode($_POST["param0"]))) {
$ret = webfm_dbdelete_file($ret);
webfm_json(array(
'status' => $ret,
'data' => t('webfm_dbdelete_file() success'),
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('file not in db'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('permission denied'),
));
}
exit;
break;
case "version":
if (isset($_POST["param0"]) && isset($_POST["param1"])) {
$op = trim(rawurldecode($_POST["param0"]));
$filename = trim(rawurldecode($_POST["param1"]));
if (strcmp($_SESSION['temp_upload']->filename, $filename) === 0) {
$ver_data = array();
$ver_data['msg'] = 'Upload Fail';
$ret = webfm_version_upload($op, $msg);
if ($ret) {
$ver_data['fid'] = $ret;
$ver_data['msg'] = t('Upload Success');
}
webfm_json(array(
'status' => $ret,
'data' => $ver_data,
));
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('invalid file name'),
));
}
}
else {
webfm_json(array(
'status' => FALSE,
'data' => t('insufficient params'),
));
}
unset($_SESSION['temp_upload']);
exit;
break;
default:
webfm_json(array(
'status' => FALSE,
'data' => t('illegal operation'),
));
exit;
break;
}
exit;
}
exit;
}
function webfm_version_upload($op, &$msg) {
global $user;
$ret = TRUE;
switch ($op) {
case WEBFM_CANCEL:
$ret = FALSE;
$msg = t('Upload Cancelled');
break;
case WEBFM_RENAME_NEW:
$ret = webfm_upload_new($msg);
break;
case WEBFM_REPLACE_RENAME:
$path = $_SESSION['temp_upload']->dest . '/' . $_SESSION['temp_upload']->filename;
if ($pos = strrpos($path, '.')) {
$name = substr($path, 0, $pos);
$ext = substr($path, $pos);
}
else {
$name = $basename;
}
$counter = 0;
do {
$temp_path = $name . '_' . $counter++ . $ext;
} while (file_exists($temp_path));
@rename($path, $temp_path);
if (file_move($_SESSION['temp_upload'], $_SESSION['temp_upload']->dest)) {
if ($_SESSION['temp_upload']->in_db == TRUE) {
if (($record = webfm_get_file_record('', $path)) === FALSE) {
$ret = FALSE;
$msg = t('Replace-Delete webfm_get_file_record fail');
break;
}
$time = @filemtime($_SESSION['temp_upload']->filepath);
$query = "UPDATE {webfm_file} SET fsize = %d, fcreatedate = %d, fversion = %d, uid = %d WHERE fid = %d";
$row = db_query($query, $_SESSION['temp_upload']->filesize, $time, $record->fversion + 1, $user->uid, $record->fid);
if ($row === FALSE) {
$ret = FALSE;
$msg = t('Replace-Delete update fail');
file_delete($path);
@rename($temp_path, $path);
}
else {
$newfile = new stdClass();
$newfile->filepath = $temp_path;
$ret = webfm_dbinsert_file($newfile, $msg, (array) $record);
if ($ret !== FALSE) {
$msg = t('Upload success');
}
}
}
else {
$ret = webfm_upload_new($msg);
}
}
else {
$ret = FALSE;
$msg = t('file_move fail');
@rename($temp_path, $path);
}
break;
case WEBFM_REPLACE_DELETE:
$path = $_SESSION['temp_upload']->dest . '/' . $_SESSION['temp_upload']->filename;
$temp_path = $path . '~';
@rename($path, $temp_path);
if (file_move($_SESSION['temp_upload'], $_SESSION['temp_upload']->dest)) {
if ($_SESSION['temp_upload']->in_db == TRUE) {
if (($record = webfm_get_file_record('', $path)) === FALSE) {
$ret = FALSE;
$msg = t('Replace-Delete webfm_get_file_record fail');
break;
}
$time = @filemtime($_SESSION['temp_upload']->filepath);
$query = "UPDATE {webfm_file} SET fsize = %d, fcreatedate = %d, fversion = %d, uid = %d WHERE fid = %d";
$row = db_query($query, $_SESSION['temp_upload']->filesize, $time, $record->fversion + 1, $user->uid, $record->fid);
if ($row === FALSE) {
$ret = FALSE;
$msg = t('Replace-Delete update fail');
file_delete($path);
@rename($temp_path, $path);
}
else {
$ret = $record->fid;
$msg = t('Upload success');
file_delete($temp_path);
}
}
else {
file_delete($temp_path);
$ret = TRUE;
$msg = t('Upload success');
}
}
else {
$ret = FALSE;
$msg = t('file_move fail');
@rename($temp_path, $path);
}
break;
default:
$ret = FALSE;
$msg = '';
break;
}
return $ret;
}
function webfm_upload_new(&$msg) {
if (file_move($_SESSION['temp_upload'], $_SESSION['temp_upload']->dest)) {
if (($ret = webfm_dbinsert_file($_SESSION['temp_upload'], $msg)) !== FALSE) {
$msg = t('Upload success');
return $ret;
}
else {
file_delete($_SESSION['temp_upload']->filepath);
return FALSE;
}
}
else {
$msg = t('file_move to ') . $_SESSION['temp_upload']->dest . t(' failed');
return FALSE;
}
}
function webfm_json($var = NULL) {
drupal_set_header('Content-Type: text/javascript; charset=utf-8');
if (isset($var)) {
echo drupal_to_js($var);
}
}
function webfm_main() {
global $base_url;
global $user;
$modulepath = drupal_get_path('module', 'webfm');
drupal_add_js($modulepath . '/js/webfm.js');
drupal_add_js('misc/collapse.js');
drupal_add_css($modulepath . '/css/webfm.css');
module_invoke_all('webfm_extend_js');
if (is_null($inline_js)) {
global $user;
$clean_url = variable_get('clean_url', 0);
$clean = $clean_url == 0 || $clean_url == '0' ? FALSE : TRUE;
$inline_js = webfm_inline_js($base_url, $clean, $user->uid);
}
$debug_link = drupal_to_js(variable_get('webfm_debug', '')) ? t('[<a href=# id="webfm-debug-link">debug</a>]') : '';
if ($user->uid == 1 || user_access('administer webfm')) {
$settings_link = t('[<a href="@link">settings...</a>]', array(
'@link' => url("admin/settings/webfm"),
));
$help_link = module_hook('help', 'page') ? t('[<a href="@link">more help...</a>]', array(
'@link' => url("admin/help/webfm"),
)) : '';
$output = '<div class="more-help-link">' . $debug_link . $settings_link . $help_link . '</div>';
}
else {
$output = '<div class="more-help-link">' . $debug_link . '</div>';
}
$output .= '<noscript><p class="err">JavaScript must be enabled in order to use webfm!</p></noscript>' . "\n";
$output .= '<div id="webfm">' . "\n";
if ($user->uid == 1 || user_access('administer webfm') || user_access('webfm upload')) {
$output .= drupal_get_form('webfm_upload_fieldset');
}
$output .= '</div>' . "\n";
return $output;
}
function webfm_upload_fieldset() {
$form = array();
$form['webfm_uploads'] = array(
'#type' => 'fieldset',
'#title' => t('File Upload'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('Uploaded file will be saved to the current directory.'),
'#prefix' => '<div class="attachments">',
'#suffix' => '</div>',
'#weight' => 30,
);
$form['webfm_uploads']['wrapper'] = array(
'#prefix' => '<div id="wfmatt-wrapper">',
'#suffix' => '</div>',
);
$form['webfm_uploads']['wrapper'] += webfm_upload_form('webfm/upload');
$form['#attributes'] = array(
'enctype' => "multipart/form-data",
);
return $form;
}
function webfm_upload_form($upload_url) {
$form['#theme'] = 'webfm_upload_form';
$form['new'] = array(
'#prefix' => '<div id="wfmatt-hide">',
'#suffix' => '</div>',
);
$form['new']['webfm_upload'] = array(
'#type' => 'file',
'#title' => t('Upload file'),
'#size' => 40,
);
$form['new']['wfmatt'] = array(
'#type' => 'button',
'#value' => t('Upload'),
'#name' => 'attach',
'#id' => 'wfmatt-button',
);
$form['webfmuploadpath'] = array(
'#type' => 'hidden',
'#value' => '',
);
$form['wfmatt-url'] = array(
'#type' => 'hidden',
'#value' => url($upload_url, NULL, NULL, TRUE),
'#attributes' => array(
'class' => 'webfmupload',
),
);
return $form;
}
function webfm_version_form($filename) {
$form['select'] = array(
'#prefix' => '<div id="replace-options">',
'#suffix' => '</div>',
'#type' => 'radios',
'#title' => t('Select File Versioning Option'),
'#options' => array(
'Replace and rename original copy of ' . $filename,
'Replace and delete original copy of ' . $filename,
'Rename new copy of ' . $filename,
'Cancel',
),
'#required' => TRUE,
);
return $form;
}
function theme_webfm_upload_form($form) {
$output = drupal_render($form);
return $output;
}
function webfm_inline_js($base_url, $clean_url, $uid) {
$js = '<script type="text/javascript">function getBaseUrl(){return ' . drupal_to_js($base_url) . ';} function getWebfmIconDir(){return ' . drupal_to_js($base_url . "/" . variable_get('webfm_icon_dir', '')) . ';} function getWebfmCleanUrl(){return ' . drupal_to_js($clean_url) . '; }function getWebfmIETreeOffset(){return ' . drupal_to_js(variable_get('webfm_ie_dd_tree_offset', '')) . ';}function getWebfmIEListOffset(){return ' . drupal_to_js(variable_get('webfm_ie_dd_list_offset', '')) . ';} function getWebfmUid(){return ' . drupal_to_js($uid) . ';} function getWebfmDateFormat(){return ' . drupal_to_js(variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY)) . ';} function getWebfmMetaName(){return ' . drupal_to_js(variable_get('webfm_display_title', '')) . ';}</script>';
drupal_set_html_head($js);
return $js;
}
function webfm_check_path($path, $root) {
if (strncmp($path, $root, strlen($root)) == 0) {
if (strlen($path) == strlen($root) || substr($path, strlen($root), 1) == '/') {
return $path;
}
}
return '';
}
function webfm_get_root_path() {
static $webfm_root_path;
if (empty($webfm_root_path)) {
$webfm_root_path = variable_get('webfm_root_dir', '');
if (empty($webfm_root_path)) {
$webfm_root_path = NULL;
}
else {
$webfm_root_path = '/' . $webfm_root_path;
}
}
return $webfm_root_path;
}
function webfm_get_access_roles($flush = FALSE) {
static $webfm_access_roles = array();
if ($flush) {
$webfm_access_roles = array();
}
if (!count($webfm_access_roles)) {
$webfm_access_roles = user_roles(0, 'access webfm');
}
return $webfm_access_roles;
}
function webfm_get_root_dirs($flush = FALSE) {
global $user;
static $webfm_roots = array();
$webfm_access_roles = webfm_get_access_roles($flush);
$webfm_roots = array();
foreach ($user->roles as $rid => $role) {
if (array_key_exists($rid, $webfm_access_roles)) {
$path = variable_get("root_dir_" . $rid, '');
if (!empty($path)) {
if (!in_array($path, $webfm_roots)) {
$webfm_roots[$rid] = "/" . $path;
}
}
}
}
if (array_key_exists(1, $webfm_access_roles)) {
$path = variable_get("root_dir_1", '');
if (!empty($path)) {
$webfm_roots[1] = "/" . $path;
}
}
return $webfm_roots;
}
function webfm_file_mod_access($webfm_file) {
if ((int) $webfm_file->perm & WEBFM_FILE_ACCESS_ROLE_FULL) {
return webfm_path_access($webfm_file->fpath);
}
return FALSE;
}
function webfm_file_view_access($webfm_file) {
if ((int) $webfm_file->perm & WEBFM_FILE_ACCESS_ROLE_VIEW) {
return webfm_path_access($webfm_file->fpath);
}
return FALSE;
}
function webfm_file_att_access($webfm_file) {
if ((int) $webfm_file->perm & WEBFM_FILE_ACCESS_ROLE_ATTACH) {
return webfm_path_access($webfm_file->fpath);
}
return FALSE;
}
function webfm_path_access($path) {
$root_dir = file_directory_path() . webfm_get_root_path();
$webfm_roots = webfm_get_root_dirs();
foreach ($webfm_roots as $key => $sub_root) {
if (webfm_check_path($path, $root_dir . $sub_root)) {
return TRUE;
}
}
return FALSE;
}
function webfm_default_file_perm() {
$perm = (int) (variable_get('webfm_file_perm_role', '') ? WEBFM_FILE_ACCESS_ROLE_VIEW : 0);
$perm += (int) (variable_get('webfm_file_perm_mod', '') ? WEBFM_FILE_ACCESS_ROLE_FULL : 0);
$perm += (int) (variable_get('webfm_file_perm_attach', '') ? WEBFM_FILE_ACCESS_ROLE_ATTACH : 0);
$perm += (int) (variable_get('webfm_file_public', '') ? WEBFM_FILE_ACCESS_PUBLIC_VIEW : 0);
return $perm;
}
function webfm_get_date_format() {
static $dateformat;
if (!$dateformat) {
$date_format_type = variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY);
switch ($date_format_type) {
case WEBFM_DATE_FORMAT_MONTH:
$dateformat = 'm/d/y g:i a';
break;
case WEBFM_DATE_FORMAT_DAY:
default:
$dateformat = 'd/m/y g:i a';
break;
}
}
return $dateformat;
}
class webfm_build_dir_list {
var $dirs = array();
var $files = array();
var $breadcrumb = array();
function webfm_build_dir_list($root, $path, $perm) {
global $user;
$bl = array(
'.',
'..',
'.htaccess',
);
$_dirs = array();
$_files = array();
$full_path = $root . $path;
if (is_dir($full_path)) {
chdir($full_path);
if ($handle = opendir('.')) {
$non_root_arr = explode('/', trim($path, '/'));
foreach ($non_root_arr as $piece) {
$this->breadcrumb[] = $piece;
}
while (($readdir = readdir($handle)) !== false) {
if (!in_array(strtolower($readdir), $bl)) {
if (is_dir($readdir)) {
$_dirs[] = $readdir;
}
if (is_file($readdir)) {
$_files[] = $readdir;
}
}
}
closedir($handle);
}
if (is_array($_dirs)) {
foreach ($_dirs as $dir) {
$dd = new stdClass();
$dd->n = $dir;
$dd->p = $path . "/" . $dir;
$dd->m = filemtime($dir) ? @filemtime($dir) : "";
$this->dirs[] = $dd;
}
}
if (is_array($_files)) {
foreach ($_files as $file) {
if ($_file = webfm_get_file_record('', $full_path . '/' . $file)) {
if ($perm == WEBFM_ADMIN || $_file->uid == $user->uid || (int) $_file->perm & WEBFM_FILE_ACCESS_ROLE_FULL || (int) $_file->perm & WEBFM_FILE_ACCESS_ROLE_VIEW) {
$fd = new stdClass();
$fd->id = $_file->fid;
if ((int) $_file->perm & WEBFM_FILE_ACCESS_ROLE_FULL) {
$fd->u = $user->uid;
}
else {
$fd->u = $_file->uid;
}
$_query = 'SELECT name FROM {users} WHERE uid = %d';
$fd->un = db_result(db_query($_query, $_file->uid));
$fd->m = @filemtime($file);
$fd->s = @filesize($file);
}
else {
continue;
}
}
else {
if ($perm == WEBFM_ADMIN) {
$fd = new stdClass();
$fd->id = 0;
$fd->u = 0;
$_query = 'SELECT name FROM {users} WHERE uid = %d';
$fd->un = db_result(db_query($_query, $fd->u));
$fd->m = @filemtime($file);
$fd->s = @filesize($file);
}
else {
continue;
}
}
if (variable_get('webfm_display_title', '') && $_file->ftitle) {
$fd->ftitle = urldecode($_file->ftitle);
}
$fd->n = $file;
$fd->p = $path;
$fd->i = 0;
if (strpos($file, ".") === FALSE) {
$fd->e = "";
}
else {
$fd->e = array_pop(explode('.', $file));
$mime_type = webfm_mime_type($file);
if (preg_match('/^image/', $mime_type)) {
if (!function_exists('exif_imagetype')) {
if ($i = @getimagesize($file)) {
if ($i[0] != 0 && $i[1] != 0) {
$fd->i = $i[2];
}
}
}
else {
if ($i = @exif_imagetype($file)) {
$fd->i = $i;
}
}
}
}
$this->files[] = $fd;
}
}
}
}
function get_dir_listing() {
return $this->dirs;
}
function get_file_listing() {
return $this->files;
}
function get_breadcrumb() {
return $this->breadcrumb;
}
}
function webfm_tree($rootpath, $path) {
if (!isset($_SESSION['tree_' . $path])) {
$tree = array();
$tree[$path] = recurse_build_tree($rootpath . $path, false);
$_SESSION['tree_' . $path] = $tree;
return $tree;
}
return $_SESSION['tree_' . $path];
}
function recurse_build_tree($dir, $full) {
if ($handle = opendir($dir)) {
while (false !== ($readdir = readdir($handle))) {
if ($readdir != '.' && $readdir != '..') {
$path = $dir . '/' . $readdir;
if (is_dir($path)) {
$tree[$readdir] = recurse_build_tree($path, $full);
}
if ($full == true) {
if (is_file($path)) {
$tree[] = $readdir;
}
}
}
}
closedir($handle);
}
return isset($tree) ? $tree : '';
}
function webfm_get_attachments($nid) {
$files = array();
$file_result = db_query('SELECT * FROM {webfm_file} f INNER JOIN {webfm_attach} a ON f.fid = a.fid WHERE a.nid = %d ORDER BY a.weight', $nid);
while ($file_record = db_fetch_object($file_result)) {
$_file = new webfm_fdesc($file_record);
if ($_file->result == TRUE) {
$files[] = $_file;
}
}
return $files;
}
function webfm_db_type_placeholder($type) {
switch ($type) {
case 'varchar':
case 'char':
case 'text':
case 'datetime':
return "'%s'";
case 'numeric':
return '%n';
case 'serial':
case 'int':
return '%d';
case 'float':
return '%f';
case 'blob':
return '%b';
}
}
function webfm_db_placeholders($arguments, $type = 'int') {
$placeholder = webfm_db_type_placeholder($type);
return implode(',', array_fill(0, count($arguments), $placeholder));
}
function webfm_get_temp_attachments($fids) {
$files = array();
$fids_arr = split(',', $fids);
$file_result = db_query('SELECT * FROM {webfm_file} WHERE fid in (' . webfm_db_placeholders($fids_arr) . ')', $fids_arr);
while ($file_record = db_fetch_object($file_result)) {
$_file = new webfm_fdesc($file_record);
if ($_file->result == TRUE) {
$files[] = $_file;
}
}
return $files;
}
class webfm_fdesc {
var $result;
function webfm_fdesc($file) {
$cwd = getcwd();
$this->result = FALSE;
$dir = dirname($file->fpath);
if (is_dir($dir)) {
if (chdir($dir)) {
if ($handle = opendir('.')) {
while (($readdir = readdir($handle)) !== false) {
if (is_dir($readdir)) {
continue;
}
if (is_file($readdir) && $readdir == basename($file->fpath)) {
$this->id = $file->fid;
$this->n = strrev(substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/')));
$this->p = $dir;
$this->e = array_pop(explode('.', $this->n));
$this->s = $file->fsize;
$this->uid = $file->uid;
$_query = 'SELECT name FROM {users} WHERE uid = %d';
$this->un = db_result(db_query($_query, $file->uid));
$this->ftitle = urldecode($file->ftitle);
$this->fdesc = urldecode($file->fdesc);
$this->fcreatedate = $file->fcreatedate;
$this->flang = urldecode($file->flang);
$this->fpublisher = urldecode($file->fpublisher);
$this->fformat = urldecode($file->fformat);
$this->fversion = $file->fversion;
$this->m = filemtime($readdir) ? @filemtime($readdir) : "";
$this->result = TRUE;
break;
}
}
closedir($handle);
}
chdir($cwd);
}
}
}
}
function webfm_sanlen($x) {
if (strlen($x) > 80) {
return substr($x, 0, 40) . "..." . substr($x, -40, 40);
}
return $x;
}
class webfm_searchFiles {
var $count = 0;
var $files = array();
var $hidefilepattern;
var $uid = 0;
function webfm_searchFiles($root_dir, $dir, $searchpattern, $regexpsearch = FALSE, $user) {
$this->hidefilepattern = "^(CVS|\\..*)\$";
$this->uid = $user;
$this
->searchFilesRecur($root_dir, $dir, $searchpattern);
}
function get_files() {
return $this->files;
}
function get_count() {
return $this->count;
}
function build_file_list($name, $path, $id) {
$sfd = new stdClass();
$sfd->n = $name;
$sfd->p = $path;
$sfd->id = $id;
$this->files[] = $sfd;
$this->count++;
}
function searchFilesRecur($root_dir, $dir, $searchpattern) {
$dir = rtrim($dir, '/');
$full_dir = $root_dir . $dir;
$handle = @opendir($full_dir);
while ($file = @readdir($handle)) {
if (@is_dir($full_dir . "/" . $file) && $file != "." && $file != "..") {
$this
->searchFilesRecur($root_dir, $dir . "/" . $file, $searchpattern);
}
else {
if (ereg(strtolower($searchpattern), strtolower($file)) && !ereg($this->hidefilepattern, $file)) {
if ($frec = webfm_get_file_record('', $full_dir . "/" . $file)) {
if ($this->uid == 1 || $this->uid == $frec->uid || webfm_file_view_access($frec)) {
$this
->build_file_list($file, $dir, $frec->fid);
}
}
else {
if ($this->uid == 1) {
$this
->build_file_list($file, $dir, 0);
}
}
}
}
}
@closedir($handle);
}
}
function webfm_send_file($fid, $attach = false) {
global $user;
$match = FALSE;
$f = false;
if ($user->uid == 1 || user_access('administer webfm')) {
$webfm_perm = WEBFM_ADMIN;
$match = TRUE;
}
else {
if (user_access('access webfm')) {
$webfm_perm = WEBFM_USER;
}
else {
if (user_access('view webfm attachments')) {
$webfm_perm = WEBFM_ATTACH_VIEW;
}
else {
$webfm_perm = 0;
}
}
}
if (is_numeric($fid)) {
if (($f = webfm_get_file_record($fid)) === FALSE) {
print theme('page', "");
return;
}
else {
if ($f->uid == $user->uid) {
$match = TRUE;
}
}
}
else {
if ($webfm_perm == WEBFM_ADMIN) {
$f = new stdClass();
$str_arr = array();
$str_arr = split('[~]', rawurldecode($fid));
$f->fpath = file_directory_path() . "/" . implode('/', $str_arr);
if (!is_file($f->fpath)) {
print theme('page', "");
return;
}
else {
$match = TRUE;
}
}
else {
print theme('page', "");
return;
}
}
if ($match == FALSE && $webfm_perm != WEBFM_ADMIN) {
if ($f->perm & WEBFM_FILE_ACCESS_PUBLIC_VIEW) {
$match = TRUE;
}
else {
if ($webfm_perm == WEBFM_USER || $webfm_perm == WEBFM_ATTACH_VIEW) {
$query = 'SELECT nid FROM {webfm_attach} WHERE fid = %d';
$result = db_query($query, $f->fid);
if ($result !== FALSE) {
while ($dbfid = db_fetch_array($result)) {
$node = node_load($dbfid['nid']);
if (node_access('view', $node)) {
$match = TRUE;
break;
}
}
}
}
}
}
if ($match == FALSE && $webfm_perm == WEBFM_USER && (webfm_file_view_access($f) || webfm_file_mod_access($f))) {
$match = TRUE;
}
if (!$match) {
drupal_access_denied();
return;
}
$name = basename($f->fpath);
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
$name = preg_replace('/\\./', '%2e', $name, substr_count($name, '.') - 1);
}
$type = webfm_mime_type($name);
$header = array();
if ($attach === '1') {
$header[] = 'Pragma: no-cache';
$header[] = 'Cache-Control: no-cache, must-revalidate';
$header[] = 'Content-Disposition: attachment; filename="' . $name . '";';
if (!empty($f->fid)) {
$cnt = array();
$cnt['dl_cnt'] = (int) $f->dl_cnt + 1;
webfm_dbupdate_file($f->fid, '', $cnt);
}
}
else {
$header[] = 'Pragma: public';
$header[] = 'Expires: 0';
$header[] = 'Cache-Control: must-revalidate, post-check=0, pre-check=0';
$header[] = 'Content-Transfer-Encoding: binary';
$header[] = 'Content-Disposition: inline; filename="' . $name . '";';
if (!empty($f->fid) && strpos($type, "application") === 0) {
$cnt = array();
$cnt['dl_cnt'] = (int) $f->dl_cnt + 1;
webfm_dbupdate_file($f->fid, '', $cnt);
}
}
$header[] = 'Content-Type: ' . $type;
$header[] = 'Content-Length: ' . (string) @filesize($f->fpath);
$header[] = 'Connection: close';
file_transfer($f->fpath, $header);
}
function webfm_dbinsert_file($file, &$error, $metadata = array()) {
global $user;
if (!isset($file->filepath)) {
$error = "No file path supplied";
return FALSE;
}
else {
$metadata['fpath'] = $file->filepath;
}
unset($metadata['fid']);
if (!isset($metadata['uid'])) {
$metadata['uid'] = $user->uid;
}
if (!isset($metadata['fsize'])) {
$metadata['fsize'] = @filesize($file->filepath);
}
if (!isset($metadata['fcreatedate'])) {
$metadata['fcreatedate'] = @filemtime($file->filepath);
}
if (!isset($metadata['perm'])) {
$metadata['perm'] = webfm_default_file_perm();
}
if (!isset($metadata['fmime'])) {
$metadata['fmime'] = webfm_mime_type($file->filepath);
}
if (!isset($metadata['fdesc'])) {
$metadata['fdesc'] = '';
}
$fields = implode(', ', array_keys($metadata));
foreach ($metadata as $key => $value) {
if (is_numeric($value)) {
$printfvalues[] = '%d';
}
else {
$printfvalues[] = "'%s'";
}
}
$printfvalues = implode(', ', $printfvalues);
$values = array_values($metadata);
$query = "INSERT INTO {webfm_file} ({$fields}) VALUES ({$printfvalues})";
$result = db_query($query, $values);
if ($result === FALSE) {
$error = $file->filepath . ' could not be inserted into db';
drupal_set_message(t('Could not insert %file into the database', array(
'%file' => $file->filepath,
)), error);
return FALSE;
}
else {
$query = "SELECT fid FROM {webfm_file} WHERE fpath = '%s'";
$result = db_query($query, $file->filepath);
if ($result !== FALSE && ($row = db_fetch_object($result))) {
return $row->fid;
}
else {
return FALSE;
}
}
}
function webfm_dbupdate_file($fid, $path = FALSE, $metadata = array()) {
if ($path) {
$metadata['fpath'] = $path;
}
foreach ($metadata as $key => $value) {
if (is_numeric($value)) {
$printfvalues[] = $key . '=%d';
}
else {
$printfvalues[] = $key . "='%s'";
}
}
$printfvalues = implode(', ', $printfvalues);
$values = array_values($metadata);
$values[] = $fid;
$query = "UPDATE {webfm_file} SET {$printfvalues} WHERE fid = %d";
$result = db_query($query, $values);
if ($result === FALSE) {
drupal_set_message(t('webfm_dbupdate_file() err: fid=%fid', array(
'%fid' => $fid,
)), error);
return FALSE;
}
return TRUE;
}
function webfm_get_extensions_regex($rid) {
static $role_ext_regex = array();
if ($rid == WEBFM_FLUSH) {
$role_ext_regex = array();
return '';
}
if (!$role_ext_regex[$rid]) {
$extensions = variable_get("webfm_extensions_" . $rid, '');
$role_ext_regex[$rid] = '/\\.(' . ereg_replace(' +', '|', preg_quote($extensions)) . ')$/i';
}
return $role_ext_regex[$rid];
}
function webfm_enum_validate($file, &$err_msg) {
global $user;
$name = $file->filename ? $file->filename : strrev(substr(strrev($file->filepath), 0, strpos(strrev($file->filepath), '/')));
if (strlen($name) > 255) {
$err_msg[] = 'file name has invalid length';
return FALSE;
}
if ($user->uid == 1 || user_access('administer webfm')) {
return TRUE;
}
$webfm_access_roles = webfm_get_access_roles();
$num_roles = 0;
$error = 0;
foreach ($user->roles as $rid => $role) {
if (array_key_exists($rid, $webfm_access_roles)) {
$num_roles++;
$regex = webfm_get_extensions_regex($rid);
if (!preg_match($regex, $name)) {
$err_msg[] = $name . ' has invalid extension for ' . $role . ' role.';
$error++;
}
}
}
return $error == $num_roles ? FALSE : TRUE;
}
function webfm_upload_validate($file, &$err_arr) {
global $user;
if ($user->uid == 1) {
return TRUE;
}
$copy_err = is_array($err_arr);
foreach ($user->roles as $rid => $name) {
$regex = webfm_get_extensions_regex($rid);
$uploadsize = variable_get("webfm_uploadsize_" . $rid, 1) * 1024 * 1024;
$usersize = variable_get("webfm_usersize_" . $rid, 1) * 1024 * 1024;
if (!preg_match($regex, $file->filename)) {
$error['extension']++;
}
if ($uploadsize && $file->filesize > $uploadsize) {
$error['uploadsize']++;
}
if ($usersize && $total_usersize + $file->filesize > $usersize) {
$error['usersize']++;
}
}
$user_roles = count($user->roles);
$valid = TRUE;
if ($error['extension'] == $user_roles) {
if ($copy_err) {
$err_arr[] = $file->filepath . " has an invalid extension";
}
form_set_error('webfm_uploads', t('%name can not be uploaded because it does not have one of the following extensions: %files-allowed.', array(
'%name' => $file->filename,
'%files-allowed' => $extensions,
)));
$valid = FALSE;
}
elseif ($error['uploadsize'] == $user_roles) {
if ($copy_err) {
$err_arr[] = $file->filepath . " exceeds the max filesize";
}
form_set_error('webfm_uploads', t('%name can not be attached to this post, because it exceeded the maximum filesize of %maxsize.', array(
'%name' => $file->filename,
'%maxsize' => format_size($uploadsize),
)));
$valid = FALSE;
}
elseif ($error['usersize'] == $user_roles) {
if ($copy_err) {
$err_arr[] = $file->filepath . " exceeds the max disk quota";
}
form_set_error('webfm_uploads', t('%name can not be attached to this post, because the disk quota of %quota has been reached.', array(
'%name' => $file->filename,
'%quota' => format_size($usersize),
)));
$valid = FALSE;
}
elseif (strlen($file->filename) > 255) {
if ($copy_err) {
$err_arr[] = $file->filepath . " exceeds the max name length";
}
form_set_error('webfm_uploads', t('The selected file can not be attached to this post, because the filename is too long.'));
$valid = FALSE;
}
return $valid ? TRUE : FALSE;
}
function webfm_get_fid($path) {
$query = "SELECT fid FROM {webfm_file} WHERE fpath = '%s'";
$result = db_query($query, $path);
if ($result !== FALSE) {
if ($row = db_fetch_object($result)) {
return $row->fid;
}
}
return FALSE;
}
function webfm_get_file_record($fid = '', $path = '') {
if (is_numeric($fid)) {
$query = "SELECT * FROM {webfm_file} WHERE fid = %d";
if (($result = db_query($query, $fid)) !== FALSE) {
if ($row = db_fetch_object($result)) {
return $row;
}
}
}
else {
if (is_string($path)) {
$query = "SELECT * FROM {webfm_file} WHERE fpath = '%s'";
if (($result = db_query($query, $path)) !== FALSE) {
if ($row = db_fetch_object($result)) {
return $row;
}
}
}
}
return FALSE;
}
function webfm_putmeta($fid, $metadata, $user, &$err) {
static $metadata_key_arr = array();
if (!count($metadata_key_arr)) {
$metadata_key_arr = array(
't' => array(
'field' => 'ftitle',
'size' => 255,
),
'd' => array(
'field' => 'fdesc',
'size' => 1024,
),
'l' => array(
'field' => 'flang',
'size' => 16,
),
'p' => array(
'field' => 'fpublisher',
'size' => 255,
),
'f' => array(
'field' => 'fformat',
'size' => 255,
),
'u' => array(
'field' => 'uid',
'size' => 10,
),
);
}
$err = "";
if (($file = webfm_get_file_record($fid)) != false) {
if ($user == 1 || $user == $file->uid || webfm_file_mod_access($file)) {
$fields = explode(',', $metadata);
$metadata = array();
foreach ($fields as $field) {
trim($field);
$key = substr($field, 0, 1);
$separator = substr($field, 1, 1);
$value = substr($field, 2, min(strlen($field) - 2, $metadata_key_arr[$key]['size']));
if (array_key_exists($key, $metadata_key_arr) && $separator == ":") {
if ($key == 'u') {
if ($user == 1) {
$uid_val = strval($value);
if (is_numeric($uid_val) && strlen($uid_val) << 11) {
if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid = %d", $uid_val)) > 0) {
$metadata[$metadata_key_arr[$key]['field']] = $uid_val;
}
else {
$err = "user not found";
return FALSE;
}
}
else {
$err = "invalid data";
return FALSE;
}
}
else {
$err = "permission denied";
return FALSE;
}
}
else {
$metadata[$metadata_key_arr[$key]['field']] = strval($value);
}
}
}
if (count($metadata)) {
$ret = webfm_dbupdate_file($fid, '', $metadata);
if ($ret) {
$err = "metadata updated";
return TRUE;
}
else {
$err = "webfm_dbupdate_file fail";
}
}
else {
if (!strlen($err)) {
$err = "no update required";
}
return TRUE;
}
}
else {
$err = "permission denied";
}
}
else {
$err = "file not found";
}
return FALSE;
}
function webfm_dbdelete_file($fid) {
if (_webfm_dbdelete_file_fid($fid)) {
_webfm_dbdelete_attach_fid($fid);
return TRUE;
}
return FALSE;
}
function _webfm_dbdelete_file_fid($fid) {
$query = 'DELETE FROM {webfm_file} WHERE fid = %d';
$result = db_query($query, $fid);
if ($result === FALSE) {
drupal_set_message(t('Query Failed: Could not delete file %fid .', array(
'%fid' => $fid,
), error));
return FALSE;
}
return TRUE;
}
function webfm_dbupdate_attach($nid, $fids) {
$i = 0;
if (!webfm_check_attach_order($nid, $fids)) {
$query = "DELETE FROM {webfm_attach} WHERE nid = %d";
if ($result = db_query($query, $nid)) {
foreach ($fids as $fid) {
if ($fid) {
webfm_dbinsert_attach($nid, $fid, $i++);
}
$flag = TRUE;
}
if ($flag === TRUE) {
return TRUE;
}
}
}
}
function webfm_check_attach_order($nid, $fids) {
$query = "SELECT fid FROM {webfm_attach} WHERE nid = %d ORDER BY weight";
$result = db_query($query, $nid);
$match = TRUE;
$i = 0;
while ($dbfid = db_fetch_array($result)) {
if ($dbfid['fid'] != $fids[$i]) {
$match = FALSE;
break;
}
$i++;
}
if ($i < count($fids)) {
$match = FALSE;
}
return $match;
}
function webfm_dbinsert_attach($nid, $fid, $weight) {
$query = 'SELECT * FROM {webfm_attach} WHERE nid = %d AND fid = %d';
$result = db_query($query, $nid, $fid);
if (db_num_rows($result) !== 0) {
drupal_set_message(t('File is already attached to this node.'));
return FALSE;
}
else {
$query = 'INSERT INTO {webfm_attach} (nid, fid, weight) VALUES (%d, %d, %d)';
$result = db_query($query, $nid, $fid, $weight);
if ($result === FALSE) {
drupal_set_message(t('Query Failed: Could not attach files to node ') . $nid);
return FALSE;
}
else {
return TRUE;
}
}
}
function webfm_dbdelete_attachments($nid) {
$query = 'DELETE FROM {webfm_attach} WHERE nid = %d';
$result = db_query($query, $nid);
if ($result === FALSE) {
drupal_set_message(t('Failed to remove file attachments for deleted node %nid', array(
'%nid' => $nid,
)));
return FALSE;
}
return TRUE;
}
function webfm_dbdelete_attach($nid, $fid) {
$query = 'DELETE FROM {webfm_attach} WHERE nid = %d AND fid = %d';
$result = db_query($query, $nid, $fid);
if ($result === FALSE) {
drupal_set_message(t('Query Failed: Could not detach file %fid from node %nid', array(
'%fid' => $fid,
'%nid' => $nid,
)));
return FALSE;
}
return TRUE;
}
function _webfm_dbdelete_attach_fid($fid) {
$query = 'DELETE FROM {webfm_attach} WHERE fid = %d';
$result = db_query($query, $fid);
if ($result === FALSE) {
return FALSE;
}
return TRUE;
}
if (module_exists('views')) {
require_once "./" . $modulepath . "/webfm_views.inc";
}