You are here

asset.node.inc in Asset 6

File

inc/asset.node.inc
View source
<?php

/**
 * Persist an asset object to the db
 *
 * @param $asset
 *   asset object with filename, filepath, filemime, and filesize properties
 * @param $form_values
 *   form_values array from asset creation form. this allows asset_save to set
 *   the defaults for fields like title, author and permissions.
 */
function asset_save($asset, $form_values = array()) {
  $path = file_directory_path();
  if (substr($asset->filepath, 0, strlen($path)) == $path) {
    $asset->filepath = trim(substr($asset->filepath, strlen($path)), '/');
  }
  $info = pathinfo($asset->filepath);
  if ($info['dirname'] == '.') {
    $info['dirname'] = '';
  }
  if ($asset->type == "directory") {
    $info['dirname'] = $form_values['parent'];
    $info['basename'] = $form_values['title'];
  }
  $default_fields = array(
    'title',
    'author',
    'description',
    'roles',
    'status',
  );
  foreach ($default_fields as $field) {
    $asset->{$field} = $form_values[$field];
  }
  $asset->uid = $asset->uid ? $asset->uid : $GLOBALS['user']->uid;
  $asset->status = $asset->status ? ASSET_PUBLIC : ASSET_PRIVATE;
  $asset->type = $asset->type ? $asset->type : 'local';
  db_query("INSERT INTO {asset}\n\t\t(type,dirname,filename,extension,filesize,uid,status,title,author,description)\n\t\tVALUES\n\t\t('%s', '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s')", $asset->type, $info['dirname'], $info['basename'], $info['extension'], $asset->filesize, $asset->uid, $asset->status, $asset->title, $asset->author, $asset->description);

  // make sure to set aid on the asset object, so modules can use it in assetapi insert
  $asset->aid = db_last_insert_id('asset', 'aid');
  if ($asset->status == ASSET_PRIVATE && is_array($asset->roles)) {
    foreach ($asset->roles as $rid => $status) {
      db_query('INSERT INTO {asset_role} (aid, rid, status) VALUES (%d, %d, %d)', array(
        $asset->aid,
        $rid,
        $rid,
      ));
    }
  }

  // We're also saving this in the files table to support the private download method
  if (!$asset->fid) {
    $mime = function_exists(mime - content - type) ? mime - content - type($info['dirname'] . "/" . $info['basename']) : "";
    $filepath = file_directory_path() . "/" . $info['dirname'] . "/" . $info['basename'];
    db_query("INSERT INTO {files}\n\t\t\t(uid, filename, filepath, filemime, filesize, status, timestamp)\n\t\t\tVALUES\n\t\t\t(%d, '%s', '%s', '%s', %d, %d, %d)", $GLOBALS['user']->uid, $info['basename'], $filepath, $mime, $asset->filesize, 1, time());
  }
  module_invoke_all('assetapi', 'insert', $asset);
  return asset_load($asset->aid);
}

/**
 * Load an asset object from db and set some default properties.
 * Taken almost exactly from node_load to utilize caching and assetapi load hook
 *
 * @param $aid
 *    id of asset to load
 */
function asset_load($param = array(), $reset = NULL) {
  static $assets = array();
  if ($reset) {
    $assets = array();
  }
  $arguments = array();
  if (is_numeric($param)) {
    if (isset($assets[$param])) {
      return is_object($assets[$param]) ? drupal_clone($assets[$param]) : $assets[$param];
    }
    $cond = 'a.aid = %d';
    $arguments[] = $param;
  }
  elseif (is_array($param)) {

    // Turn the conditions into a query.
    foreach ($param as $key => $value) {
      $cond[] = 'a.' . db_escape_string($key) . " = '%s'";
      $arguments[] = $value;
    }
    $cond = implode(' AND ', $cond);
  }
  else {
    return false;
  }

  // Retrieve the asset.
  $asset = db_fetch_object(db_query('SELECT a.* FROM {asset} a WHERE ' . $cond, $arguments));
  if (!$asset) {
    return false;
  }
  $dirname_tmp = $asset->dirname ? $asset->dirname . '/' : $asset->dirname;
  $result = db_query('SELECT * FROM {asset_role} WHERE aid = %d', $asset->aid);
  while ($role = db_fetch_array($result)) {
    $asset->roles[$role['rid']] = $role['status'] ? $role['rid'] : 0;
  }
  $asset->filepath = file_create_path($dirname_tmp . $asset->filename);
  $asset->url = file_create_url($dirname_tmp . $asset->filename);
  $asset->extension = strtolower($asset->extension);
  $asset->title = $asset->title ? $asset->title : $asset->filename;
  if ($asset->type == 'directory' && $asset->dirname == '' && $asset->filename == $GLOBALS['user']->name) {
    $asset->title = t('My Assets');
  }
  if ($asset->aid) {
    if ($extra = module_invoke_all('assetapi', 'load', $asset)) {
      foreach ($extra as $key => $value) {
        $asset->{$key} = $value;
      }
    }
    $assets[$asset->aid] = is_object($asset) ? drupal_clone($asset) : $asset;
  }
  return $asset;
}

/**
 * Invoke a widget hook.
 */
function _content_widget_invoke($op, &$node) {
  $type_name = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);
  $type = content_types($type_name);
  $widget_types = _content_widget_types();
  $return = array();
  if (count($type['fields'])) {
    foreach ($type['fields'] as $field) {
      if ($field['type'] == 'asset') {

        //Saving asset info to node
        $node->{$field}['field_name'] = $_POST[$field['field_name']];
        $node->{$field['field_name']}[0]['options'] = $node->{$field['field_name']}[0]['value'];
      }

      //

      /* $node_field = isset($node->$field['field_name']) ? $node->$field['field_name'] : array();

            $module = $widget_types[$field['widget']['type']]['module'];
            $function = $module .'_widget';
            if (function_exists($function)) {
              // If we're building a node creation form, pre-fill with default values
             // if ($op == 'prepare form values' && empty($node->nid)) {
              //  $node_field = array_merge($node_field, content_default_value($node, $field, $node_field));
              //}

              $result = $function($op, $node, $field, $node_field);
              if (is_array($result) && $op == 'form') {
                $result[$field['field_name']]['#weight'] = $field['widget']['weight'];
              }
              if (is_array($result)) {
                $return = array_merge($return, $result);
              }
              else if (isset($result)) {
                $return[] = $result;
              }
            }
            // test for values in $node_field in case modules added items
            if (is_object($node) && (isset($node->$field['field_name']) || count($node_field))) {
              $node->$field['field_name'] = $node_field;
            }*/
    }
  }
  return $return;
}

/**
 * Implementation of hook_nodeapi()
 * This is where we build the asset_node records.
 */
function asset_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

  //print_r($op);
  switch ($op) {
    case 'insert':
    case 'update':
      _content_widget_invoke($op, $node);

      // clear previous count
      db_query('DELETE FROM {asset_node} WHERE nid = %d', $node->nid);

      // only update if using a format that includes the asset filter
      $filters = filter_list_format($node->format);
      if (!$filters['asset/0']) {
        return;
      }
      $refs = array();
      foreach (asset_get_macros($node->body) as $macro) {
        $refs[$macro['aid']]++;
      }
      foreach ($refs as $aid => $ref) {
        db_query('INSERT INTO {asset_node} (aid, nid, refs) VALUES (%d, %d, %d)', $aid, $node->nid, $ref);
      }
      break;
    case 'load':
      $result = db_query('SELECT * FROM {asset_node} WHERE nid = %d AND refs > 0', $node->nid);
      while ($asset = db_fetch_object($result)) {
        $additions['assets'][] = asset_load($asset->aid);
      }
      return $additions;
    case 'view':
      foreach ($node as $fieldname => $value) {
        if (substr($fieldname, 0, 6) == "field_") {

          // For each cck field, check if it's an asset field
          $fields = content_fields($fieldname, $node->type);
          if ($fields['type'] == "asset") {

            // The asset computer name is "value"
            $assetcheck = 1;
            foreach (array_keys($node->{$fieldname}) as $key) {

              // Add the html code for the preview
              if (!empty($value[$key]['aid'])) {
                $value[$key]['value'] = asset_preview($value[$key]['aid']);
              }
            }
          }
        }
      }
      break;
  }
}

/**
 * Implementation of hook_filter().
 */
function asset_filter($op, $delta = 0, $format = -1, $text = '') {
  switch ($op) {
    case 'list':
      return array(
        0 => t('Inline file assets'),
      );
    case 'description':
      return t('Add formatted file assets to your posts.');
    case 'process':
      foreach (asset_get_macros($text) as $unexpanded_macro => $macro) {
        $expanded_macro = asset_render_macro($macro);
        $text = str_replace($unexpanded_macro, $expanded_macro, $text);
      }
      return $text;
    default:
      return $text;
  }
}

/**
 * Implementation of hook_filter_tips().
 */
function asset_filter_tips($delta, $format, $long = false) {
  if ($long) {
    return t('Inline assets are allowed.  Use the Insert Assets link or the WYSIWYG editor button to insert the proper format.');
  }
  else {
    return t('Inline assets are allowed.');
  }
}

Functions

Namesort descending Description
asset_filter Implementation of hook_filter().
asset_filter_tips Implementation of hook_filter_tips().
asset_load Load an asset object from db and set some default properties. Taken almost exactly from node_load to utilize caching and assetapi load hook
asset_nodeapi Implementation of hook_nodeapi() This is where we build the asset_node records.
asset_save Persist an asset object to the db
_content_widget_invoke Invoke a widget hook.