<?php
// $Id: apture.module,v 1.1.4.9 2009/08/11 20:37:05 ubicity Exp $

/**
 * @file
 * Apture module for Drupal.
 *
 * This module places the apture button in your drupal editing page so that
 * users can embed and/or link rich media into their drupal posts through the 
 * apture media hub.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. See the LICENSE.txt file for more details. 
 */
 
function apture_plugin_attributes() {
    global $base_url;
    return array(
        "domain"=>"http://www.apture.com", 
        "baseurl"=>urlencode($base_url),
        "version"=>"dp6_1-5",
        "platform"=>"Drupal",
        "configUrl"=>urlencode($base_url."?q=admin/settings/apture/editorsetup")
    );
}

function apture_init() {
    if (function_exists('drupal_add_js')) 
        drupal_add_js(array('apture' => array('basePath' => base_path())), 'setting');
}

function apture_enable() {
    drupal_set_message(t('Apture module was successfully enabled. Go to a content creation page and click the Apture button on top of the editor to get started.'));
}

function apture_footer($main = 0) {
    $token = variable_get('apture_token', '');
    $plugin = apture_plugin_attributes(); 
    $is_valid_edit_page = apture_valid_editing_node();
    
    if ($is_valid_edit_page) {
        $script = '<script id="aptureScript" type="text/javascript" src="'.$plugin['domain'].'/js/aptureEdit.js?platform='.$plugin['platform'].'&plugin='.$plugin['version'].'&baseurl='.$plugin['baseurl'].'&configUrl='.$plugin['configUrl'].'&siteToken='.$token.'" charset="utf-8"></script>';
    } else {
        $script = '<script id="aptureScript" type="text/javascript" src="'.$plugin['domain'].'/js/apture.js?siteToken='.$token.'" charset="utf-8"></script>';
    }
    return $script;
}

function apture_valid_editing_node() {
    $defaults = array();
    $node_types = array_map('check_plain', node_get_types('names'));
    foreach ($node_types as $key => $value)
        $defaults[$key] = $key;

    $node_types = variable_get('apture_node_types', $defaults);
  
    if (arg(2) == 'edit' && is_numeric(arg(1))) {
        $type = db_result(db_query("SELECT type FROM {node} WHERE nid=%d", arg(1)));
    } else {
        $type = arg(2);
    }    
    
    $is_content_add_or_edit_node = (arg(0) == 'node' && ((arg(1) == 'add') || (arg(2) == 'edit')) && in_array($type, $node_types, true));
    $is_block_add_or_edit_node = ((arg(0) == 'admin') && (arg(1) == 'build') && (arg(2) == 'block') && ((arg(3) == 'add') || (arg(3) == 'configure')));
    
    return $is_content_add_or_edit_node || $is_block_add_or_edit_node;
}

function apture_menu () {
    $items = array();      

    $items['admin/settings/apture'] = array(
        'title' => t('Apture'),
        'description' => t('Configuration Settings for Apture Integration.'),
        'page callback' => 'drupal_get_form', 
        'page arguments' => array('apture_settings'),
        'access arguments' => array('access administration pages'),
        'type' => MENU_NORMAL_ITEM
    );    

    $items['admin/settings/apture/editorsetup'] = array(
        'page callback' => 'apture_editor_setup',
        'access arguments' => array('access administration pages'),
        'type' => MENU_CALLBACK
    );

    return $items;  
}

function apture_settings() {
    drupal_set_message(t("Note: if you previously manually added the Apture script to your drupal site template, you'll need to remove it to enable Apture to function properly."));
    apture_check_filter();
    $form['apture_token'] = array(
        '#type' => 'textfield',
        '#title' => t('Apture Site Token'),
        '#size' => '30',
        '#default_value' => variable_get('apture_token', ""),
        '#description' => t('Paste the Site Token provided by Apture when you registered this site.'),
    );
    
    $defaults = array();
    $node_types = array_map('check_plain', node_get_types('names'));
    foreach ($node_types as $key => $value)
        $defaults[$key] = $key;
    
    $form['apture_node_types'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Enable Apture for following content types'),
        '#default_value' => variable_get('apture_node_types', $defaults),
        '#options' => $node_types
    );    
    return system_settings_form($form);
}

function apture_check_filter() {
    $needed_tags = array('a','img','div');
    $default_input_format = filter_format_load(variable_get('filter_default_format', 1));
    $filters = filter_list_format($default_input_format->format);

    foreach ($filters as $id => $filter) {
        if ($filter->name == 'HTML filter') {
            $allowed_tags = preg_split('/\s+|<|>/', variable_get("allowed_html_". $default_input_format->format, '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>'), -1, PREG_SPLIT_NO_EMPTY);
            $diff = array_diff($needed_tags, $allowed_tags);
            if (!empty($diff))
                drupal_set_message(t('Your input filter currently removes tags required for Apture enabled links and embeds. Please add following tags to your input filter: %tags', array('%tags' => implode(', ', $diff))), 'warning');
            return false;
        }
    }
    return true;
}

function apture_editor_setup() {
    echo drupal_get_form('apture_editor_setup_form');
}

function apture_editor_setup_form() {
    $form['apture_token'] = array('#type' => 'hidden', '#value' => $_GET['siteToken']);
    $form['submit'] = array('#type' => 'submit', '#value'=>t('Install Token'));
    $form['#submit'] = array('apture_editor_setup_form_submit');
    $form['#validate'] = array('apture_editor_setup_form_validate');
    return $form;
}

function apture_editor_setup_form_validate($form, &$form_state) {
    apture_sitetoken_validate($form, $form_state);
}

function apture_editor_setup_form_submit($form, &$form_state) {
    apture_sitetoken_submit($form, $form_state);
    echo "<html><head><body><h3 style='color:#003399'>ALL DONE!</h3></body></head></html>";
    die;
}

function apture_sitetoken_validate($form, &$form_state) {
    $token = $form['apture_token']['#value'];
    if (strlen($token) != strlen(strip_tags($token))) {
        form_set_error('apture_token', t('Invalid apture site token') );
    }
}

function apture_sitetoken_submit($form, &$form_state) {
    $token = $form['apture_token']['#value'];
    $form_state['values']['apture_token'] = $token;
    variable_set('apture_token', check_plain($token));
}
