Example #1
0
 /**
  * {@inheritDocs}
  */
 public function match($pathinfo)
 {
     // The 'q' variable is pervasive in Drupal, so it's best to just keep
     // it even though it's very un-Symfony.
     $path = drupal_get_normal_path(substr($pathinfo, 1));
     if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
         menu_rebuild();
     }
     $original_map = arg(NULL, $path);
     $parts = array_slice($original_map, 0, MENU_MAX_PARTS);
     $ancestors = menu_get_ancestors($parts);
     $router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();
     if ($router_item) {
         // Allow modules to alter the router item before it is translated and
         // checked for access.
         drupal_alter('menu_get_item', $router_item, $path, $original_map);
         // The requested path is an unalaised Drupal route.
         return array('_drupal' => true, '_controller' => function ($_router_item) {
             $router_item = $_router_item;
             if (!$router_item['access']) {
                 throw new AccessDeniedException();
             }
             if ($router_item['include_file']) {
                 require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
             }
             return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
         }, '_route' => $router_item['path']);
     }
     throw new ResourceNotFoundException();
 }
Example #2
0
 /**
  * Writes a log messages and retrieves it via the REST API.
  */
 public function testWatchdog()
 {
     // Write a log message to the DB.
     $this->container->get('logger.channel.rest')->notice('Test message');
     // Get the ID of the written message.
     $id = db_query_range("SELECT wid FROM {watchdog} WHERE type = :type ORDER BY wid DESC", 0, 1, array(':type' => 'rest'))->fetchField();
     // Create a user account that has the required permissions to read
     // the watchdog resource via the REST API.
     $account = $this->drupalCreateUser(array('restful get dblog'));
     $this->drupalLogin($account);
     $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => $id, '_format' => $this->defaultFormat]), 'GET');
     $this->assertResponse(200);
     $this->assertHeader('content-type', $this->defaultMimeType);
     $log = Json::decode($response);
     $this->assertEqual($log['wid'], $id, 'Log ID is correct.');
     $this->assertEqual($log['type'], 'rest', 'Type of log message is correct.');
     $this->assertEqual($log['message'], 'Test message', 'Log message text is correct.');
     // Request an unknown log entry.
     $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => 9999, '_format' => $this->defaultFormat]), 'GET');
     $this->assertResponse(404);
     $decoded = Json::decode($response);
     $this->assertEqual($decoded['message'], 'Log entry with ID 9999 was not found', 'Response message is correct.');
     // Make a bad request (a true malformed request would never be a route match).
     $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => 0, '_format' => $this->defaultFormat]), 'GET');
     $this->assertResponse(400);
     $decoded = Json::decode($response);
     $this->assertEqual($decoded['message'], 'No log entry ID was provided', 'Response message is correct.');
 }
/**
 * Perform a single batch operation.
 *
 * Callback for batch_set().
 *
 * @param $MULTIPLE_PARAMS
 *   Additional parameters specific to the batch. These are specified in the
 *   array passed to batch_set().
 * @param $context
 *   The batch context array, passed by reference. This contains the following
 *   properties:
 *   - 'finished': A float number between 0 and 1 informing the processing
 *     engine of the completion level for the operation. 1 (or no value
 *     explicitly set) means the operation is finished: the operation will not
 *     be called again, and execution passes to the next operation or the
 *     callback_batch_finished() implementation. Any other value causes this
 *     operation to be called again; however it should be noted that the value
 *     set here does not persist between executions of this callback: each time
 *     it is set to 1 by default by the batch system.
 *   - 'sandbox': This may be used by operations to persist data between
 *     successive calls to the current operation. Any values set in
 *     $context['sandbox'] will be there the next time this function is called
 *     for the current operation. For example, an operation may wish to store a
 *     pointer in a file or an offset for a large query. The 'sandbox' array key
 *     is not initially set when this callback is first called, which makes it
 *     useful for determining whether it is the first call of the callback or
 *     not:
 *     @code
 *       if (empty($context['sandbox'])) {
 *         // Perform set-up steps here.
 *       }
 *     @endcode
 *     The values in the sandbox are stored and updated in the database between
 *     http requests until the batch finishes processing. This avoids problems
 *     if the user navigates away from the page before the batch finishes.
 *   - 'message': A text message displayed in the progress page.
 *   - 'results': The array of results gathered so far by the batch processing.
 *     This array is highly useful for passing data between operations. After
 *     all operations have finished, this is passed to callback_batch_finished()
 *     where results may be referenced to display information to the end-user,
 *     such as how many total items were processed.
 */
function callback_batch_operation($MULTIPLE_PARAMS, &$context)
{
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_node'] = 0;
        $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
    }
    // For this example, we decide that we can safely process
    // 5 nodes at a time without a timeout.
    $limit = 5;
    // With each pass through the callback, retrieve the next group of nids.
    $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
    while ($row = db_fetch_array($result)) {
        // Here we actually perform our processing on the current node.
        $node = node_load($row['nid'], NULL, TRUE);
        $node->value1 = $options1;
        $node->value2 = $options2;
        node_save($node);
        // Store some result for post-processing in the finished callback.
        $context['results'][] = check_plain($node->title);
        // Update our progress information.
        $context['sandbox']['progress']++;
        $context['sandbox']['current_node'] = $node->nid;
        $context['message'] = t('Now processing %node', array('%node' => $node->title));
    }
    // Inform the batch engine that we are not finished,
    // and provide an estimation of the completion level we reached.
    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
}
 /**
  * Check the enabled Garland blocks are correctly copied over.
  */
 function testNewDefaultThemeBlocks()
 {
     // Create administrative user.
     $adminuser = $this->drupalCreateUser(array('administer themes'));
     $this->drupalLogin($adminuser);
     // Ensure no other theme's blocks are in the block table yet.
     $count = db_query_range("SELECT 1 FROM {block} WHERE theme NOT IN ('garland', 'seven')", 0, 1)->fetchField();
     $this->assertFalse($count, t('Only Garland and Seven have blocks.'));
     // Populate list of all blocks for matching against new theme.
     $blocks = array();
     $result = db_query("SELECT * FROM {block} WHERE theme = 'garland'");
     foreach ($result as $block) {
         // $block->theme and $block->bid will not match, so remove them.
         unset($block->theme, $block->bid);
         $blocks[$block->module][$block->delta] = $block;
     }
     // Turn on the Stark theme and ensure that it contains all of the blocks
     // that Garland did.
     theme_enable(array('stark'));
     variable_set('theme_default', 'stark');
     $result = db_query("SELECT * FROM {block} WHERE theme='stark'");
     foreach ($result as $block) {
         unset($block->theme, $block->bid);
         $this->assertEqual($blocks[$block->module][$block->delta], $block, t('Block %name matched', array('%name' => $block->module . '-' . $block->delta)));
     }
 }
/**
 * Convert project repository data.
 */
function cvs_to_versioncontrol_project_update_2()
{
    // This determines how many projects will be processed in each batch run. A reasonable
    // default has been chosen, but you may want to tweak depending on your setup.
    $limit = 100;
    // Multi-part update
    if (!isset($_SESSION['cvs_to_versioncontrol_project_update_2'])) {
        $_SESSION['cvs_to_versioncontrol_project_update_2'] = 0;
        $_SESSION['cvs_to_versioncontrol_project_update_2_max'] = db_result(db_query("SELECT COUNT(*) FROM {cvs_projects}"));
    }
    // Pull the next batch of users.
    $projects = db_query_range("SELECT p.nid, p.rid, p.directory, r.modules FROM {cvs_projects} p INNER JOIN {cvs_repositories} r ON p.rid = r.rid ORDER BY p.nid", $_SESSION['cvs_to_versioncontrol_project_update_2'], $limit);
    // Loop through each project.
    while ($project = db_fetch_object($projects)) {
        // Add the repo module, and chop off the trailing slash.
        $directory = '/' . trim($project->modules) . drupal_substr($project->directory, 0, drupal_strlen($project->directory) - 1);
        db_query("INSERT INTO {versioncontrol_project_projects} (nid, repo_id, directory) VALUES (%d, %d, '%s')", $project->nid, $project->rid, $directory);
        $_SESSION['cvs_to_versioncontrol_project_update_2']++;
    }
    if ($_SESSION['cvs_to_versioncontrol_project_update_2'] >= $_SESSION['cvs_to_versioncontrol_project_update_2_max']) {
        $count = $_SESSION['cvs_to_versioncontrol_project_update_2_max'];
        unset($_SESSION['cvs_to_versioncontrol_project_update_2']);
        unset($_SESSION['cvs_to_versioncontrol_project_update_2_max']);
        return array(array('success' => TRUE, 'query' => t('Converted @count project repository entries.', array('@count' => $count))));
    }
    return array('#finished' => $_SESSION['cvs_to_versioncontrol_project_update_2'] / $_SESSION['cvs_to_versioncontrol_project_update_2_max']);
}
 /**
  * Gets a range of orphaned comment IDs.
  *
  * Orphaned comments are those which are associated with an user and / or node
  * that for some reason no longer exist on the site
  *
  * @param int $limit
  *   The number of records to retrieve.
  *
  * @return array
  *   An indexed array containing the relevant comment IDs, or an empty array
  *   if there is no result set.
  */
 protected function getOrphanedItems($limit)
 {
     return db_query_range('
   SELECT cid FROM {comment} c
   LEFT JOIN {users} u ON c.uid = u.uid
   LEFT JOIN {node} n ON c.nid = n.nid
   WHERE u.uid IS NULL OR n.nid IS NULL', 0, $limit)->fetchCol();
 }
Example #7
0
 /**
  * Overrides Drupal\Core\Queue\System::claimItem().
  *
  * Unlike Drupal\Core\Queue\System::claimItem(), this method provides a
  * default lease time of 0 (no expiration) instead of 30. This allows the item
  * to be claimed repeatedly until it is deleted.
  */
 public function claimItem($lease_time = 0)
 {
     $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE name = :name ORDER BY item_id ASC', 0, 1, array(':name' => $this->name))->fetchObject();
     if ($item) {
         $item->data = unserialize($item->data);
         return $item;
     }
     return FALSE;
 }
Example #8
0
 /**
  * Processes a payment POST from the CyberSource Hosted Order Page API.
  */
 public static function post()
 {
     if (!uc_cybersource_hop_include()) {
         \Drupal::logger('uc_cybersource_hop')->error('Unable to receive HOP POST due to missing or unreadable HOP.php file.');
         drupal_add_http_header('Status', '503 Service unavailable');
         print $this->t('The site was unable to receive a HOP post because of a missing or unreadble HOP.php');
         exit;
     }
     $verify = VerifyTransactionSignature($_POST);
     \Drupal::logger('uc_cybersource_hop')->notice('Receiving payment notification at URL for order @orderNumber', array('@orderNumber' => $_POST['orderNumber']));
     if (!isset($_POST['orderNumber'])) {
         \Drupal::logger('uc_cybersource_hop')->error('CS HOP attempted with invalid order number.');
         return;
     }
     if (!$verify) {
         \Drupal::logger('uc_cybersource_hop')->notice('Receiving invalid payment notification at URL for order @orderNumber. <pre>@debug</pre>', array('@orderNumber' => $_POST['orderNumber'], '@debug' => print_r($_POST, TRUE)));
         return;
     }
     // Assign posted variables to local variables.
     $decision = SafeMarkup::checkPlain($_POST['decision']);
     $reason_code = SafeMarkup::checkPlain($_POST['reasonCode']);
     $reason = _parse_cs_reason_code($reason_code);
     $payment_amount = SafeMarkup::checkPlain($_POST['orderAmount']);
     $payment_currency = SafeMarkup::checkPlain($_POST['paymentCurrency']);
     $request_id = SafeMarkup::checkPlain($_POST['requestID']);
     $request_token = SafeMarkup::checkPlain($_POST['orderPage_requestToken']);
     $reconciliation_id = SafeMarkup::checkPlain($_POST['reconciliationID']);
     $order_id = SafeMarkup::checkPlain($_POST['orderNumber']);
     $payer_email = SafeMarkup::checkPlain($_POST['billTo_email']);
     $order = Order::load($_POST['orderNumber']);
     switch ($decision) {
         case 'ACCEPT':
             \Drupal::logger('uc_cybersource_hop')->notice('CyberSource verified successful payment.');
             $duplicate = (bool) db_query_range('SELECT 1 FROM {uc_payment_cybersource_hop_post} WHERE order_id = :order_id AND decision = :decision', 0, 1, array(':order_id' => $order_id, ':decision' => 'ACCEPT'))->fetchField();
             if ($duplicate) {
                 \Drupal::logger('uc_cybersource_hop')->notice('CS HOP transaction for order @order-id has been processed before.', array('@order_id' => $order_id));
                 return;
             }
             db_insert('uc_payment_cybersource_hop_post')->fields(array('order_id' => $order_id, 'request_id' => $request_id, 'request_token' => $request_token, 'reconciliation_id' => $reconciliation_id, 'gross' => $payment_amount, 'decision' => $decision, 'reason_code' => $reason_code, 'payer_email' => $payer_email, 'received' => REQUEST_TIME))->execute();
             $comment = $this->t('CyberSource request ID: @txn_id', array('@txn_id' => $request_id));
             uc_payment_enter($order_id, 'cybersource_hop', $payment_amount, $order->getUserId(), NULL, $comment);
             uc_cart_complete_sale($order);
             uc_order_comment_save($order_id, 0, $this->t('Payment of @amount @currency submitted through CyberSource with request ID @rid.', array('@amount' => $payment_amount, '@currency' => $payment_currency, '@rid' => $request_id)), 'order', 'payment_received');
             break;
         case 'ERROR':
             uc_order_comment_save($order_id, 0, $this->t("Payment error:@reason with request ID @rid", array('@reason' => $reason, '@rid' => '@request_id')), 'admin');
             break;
         case 'REJECT':
             uc_order_comment_save($order_id, 0, $this->t("Payment is rejected:@reason with request ID @rid", array('@reason' => $reason, '@rid' => '@request_id')), 'admin');
             break;
         case 'REVIEW':
             $order->setStatusId('review')->save();
             uc_order_comment_save($order_id, 0, $this->t('Payment is in review & not complete: @reason. Request ID @rid', array('@reason' => $reason, '@rid' => '@request_id')), 'admin');
             break;
     }
 }
 /**
  * Confirms that range queries work and return the correct result.
  */
 function testRangeQuery()
 {
     // Test if return correct number of rows.
     $range_rows = db_query_range("SELECT name FROM {test} ORDER BY name", 1, 3)->fetchAll();
     $this->assertEqual(count($range_rows), 3, 'Range query work and return correct number of rows.');
     // Test if return target data.
     $raw_rows = db_query('SELECT name FROM {test} ORDER BY name')->fetchAll();
     $raw_rows = array_slice($raw_rows, 1, 3);
     $this->assertEqual($range_rows, $raw_rows);
 }
 /**
  * {@inheritdoc}
  *
  * @see user_login_authenticate_validate().
  */
 public function authenticate(RequestInterface $request)
 {
     $username = $request->getUser();
     $password = $request->getPassword();
     // Do not allow any login from the current user's IP if the limit has been
     // reached. Default is 50 failed attempts allowed in one hour. This is
     // independent of the per-user limit to catch attempts from one IP to log
     // in to many different user accounts.  We have a reasonably high limit
     // since there may be only one apparent IP for all users at an institution.
     if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
         throw new FloodException(format_string('Rejected by ip flood control.'));
     }
     if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
         if (!($uid = db_query_range("SELECT uid FROM {users} WHERE LOWER(mail) = LOWER(:mail) AND status = 1", 0, 1, array(':mail' => $username))->fetchField())) {
             // Always register an IP-based failed login event.
             flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600), ip_address());
             return null;
         } else {
             $username = db_query_range("SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:mail) AND status = 1", 0, 1, array(':mail' => $username))->fetchField();
         }
     } else {
         if (!($uid = db_query_range("SELECT uid FROM {users} WHERE name = :name AND status = 1", 0, 1, array(':name' => $username))->fetchField())) {
             // Always register an IP-based failed login event.
             flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600), ip_address());
             return null;
         }
     }
     if (variable_get('user_failed_login_identifier_uid_only', false)) {
         // Register flood events based on the uid only, so they apply for any
         // IP address. This is the most secure option.
         $identifier = $uid;
     } else {
         // The default identifier is a combination of uid and IP address. This
         // is less secure but more resistant to denial-of-service attacks that
         // could lock out all users with public user names.
         $identifier = $uid;
         // . '-' . ip_address();
     }
     // Don't allow login if the limit for this user has been reached.
     // Default is to allow 5 failed attempts every 6 hours.
     if (flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
         // We are not limited by flood control, so try to authenticate.
         if ($uid = user_authenticate($username, $password)) {
             // Clear the user based flood control.
             flood_clear_event('failed_login_attempt_user', $identifier);
             $user = user_load($uid);
             return user_load($uid);
         }
         flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 3600), $identifier);
     } else {
         flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 3600), $identifier);
         throw new FloodException(format_string('Rejected by user flood control.'));
     }
 }
 /**
  * Test controller action 2.
  */
 public function test2()
 {
     $result = db_query_range('SELECT * FROM node');
     $taxonomies = array('Innovation' => array('items' => array('New fans', 'New materials')), 'Current Technology' => array('items' => array('Fans')));
     $taxonomies['nodes'] = count($result);
     foreach ($result as $record) {
         // Perform operations on $record->title, etc. here.
         $taxonomies[$record->title] = $record->title;
     }
     $response = new Response();
     $response->setContent(json_encode($taxonomies));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Example #12
0
/**
 * Find node title matches.
 * 
 * Some code from CCK's nodereference.module
 */
function _notifications_node_references($string, $match = 'contains', $types = array(), $limit = 10)
{
    $match_operators = array('contains' => "LIKE '%%%s%%'", 'equals' => "= '%s'", 'starts_with' => "LIKE '%s%%'");
    if ($types) {
        $where[] = 'n.type IN (' . db_placeholders($types, 'char') . ') ';
        $args = $types;
    }
    $where[] = 'n.title ' . (isset($match_operators[$match]) ? $match_operators[$match] : $match_operators['contains']);
    $args[] = $string;
    $sql = db_rewrite_sql('SELECT n.nid, n.title, n.type FROM {node} n WHERE ' . implode(' AND ', $where) . ' ORDER BY n.title, n.type');
    $result = db_query_range($sql, $args, 0, $limit);
    $references = array();
    while ($node = db_fetch_object($result)) {
        $references[$node->nid] = array('title' => $node->title, 'rendered' => check_plain($node->title));
    }
    return $references;
}
Example #13
0
    /**
     * Page callback showing ZG results.
     *
     * @return string
     *   Rendered page content.
     */
    public function page()
    {
        $limit = REQUEST_TIME - Statistics::ONEDAY * $this->days;
        drupal_set_title(t('Zeitgeist over the last @days days', array('@days' => $this->days)), PASS_THROUGH);
        $height = $this->getHeight();
        $ar_searches = array();
        $sql = <<<SQL
SELECT DISTINCT zg.search, count(zg.ts) AS nts
FROM {zeitgeist} zg
WHERE zg.ts >= :ts
GROUP BY zg.search
ORDER BY nts DESC, zg.search ASC
SQL;
        // No access control on this table.
        $results = db_query_range($sql, 0, $height * 3, array(':ts' => $limit));
        foreach ($results as $result) {
            if ($result->search == '') {
                $result->search = '&lt;vide&gt;';
            }
            $ar_searches[$result->search] = $result->nts;
        }
        $results_count = count($ar_searches);
        $break = $results_count / 3;
        $rows = array();
        $offset_in_column = 0;
        foreach ($ar_searches as $search => $count) {
            if ($offset_in_column < $break) {
                $rows[$offset_in_column] = array($search, $count, NULL, NULL, NULL, NULL);
            } elseif ($offset_in_column < 2 * $break) {
                $rows[$offset_in_column - $break][2] = $search;
                $rows[$offset_in_column - $break][3] = $count;
            } else {
                $rows[$offset_in_column - 2 * $break][4] = $search;
                $rows[$offset_in_column - 2 * $break][5] = $count;
            }
            $offset_in_column++;
        }
        $header = array(t('Search'), t('#'), t('Search'), t('#'), t('Search'), t('#'));
        $attributes = array();
        $ret = array();
        $ret['items'] = array('#theme' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => $attributes);
        $ret['note'] = array('#markup' => '<p>' . t('Searches below the pager <a href="!limit">limit</a> are not included in this list.', array('!limit' => url(ZGPATHSETTINGS))) . "</p>\n");
        return $ret;
    }
Example #14
0
/**
 * Implements hook_autosave_prevent_alter().
 *
 * @param $prevent_autosave
 *   Set this to TRUE to prevent autosaving.
 *
 *   More useful parameters are in $_POST.
 */
function hook_autosave_prevent_alter(&$prevent_autosave)
{
    $path = $_POST['autosave_form_path'];
    $path_args = explode("/", $path);
    // check if node has just been saved - if it has then it's because AS ajax fired off as user was submitting
    // if it had just been submitted - no need to AS now
    //    - easy to figure out if we are submitting an edit to existing node
    //    - little harder if we have just added a node
    if ($path_args[0] == 'node') {
        // update case
        if (is_numeric($path_args[1])) {
            $submitted = node_load($path_args[1]);
        } else {
            // add case
            $submitted = db_query_range("SELECT created AS changed FROM {node} WHERE uid = :uid and type = :type ORDER BY created DESC", 0, 1, array(':uid' => $user->uid, ':type' => str_replace("-", "_", $path_args[2])))->fetchObject();
        }
        $prevent_autosave = $submitted && REQUEST_TIME - $submitted->changed < variable_get('autosave_period', 10) ? TRUE : $prevent_autosave;
    }
}
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $account = NULL)
 {
     $form['file'] = array('#type' => 'details', '#title' => $this->t('Administration'));
     // Drop out early if we don't even have any files uploaded.
     if (!db_query_range('SELECT 1 FROM {uc_files}', 0, 1)->fetchField()) {
         $form['file']['file_message'] = array('#prefix' => '<p>', '#markup' => $this->t('You must add files at the <a href=":url">Ubercart file download administration page</a> in order to attach them to a user.', [':url' => Url::fromRoute('uc_file.downloads', [], ['query' => ['destination' => 'user/' . $account->id() . '/edit']])->toString()]), '#suffix' => '</p>');
         return $form;
     }
     // Table displaying current downloadable files and limits.
     $form['file']['download']['#theme'] = 'uc_file_hook_user_file_downloads';
     $form['file']['download']['file_download']['#tree'] = TRUE;
     $downloadable_files = array();
     $file_downloads = db_query("SELECT * FROM {uc_file_users} ufu INNER JOIN {uc_files} uf ON ufu.fid = uf.fid WHERE ufu.uid = :uid ORDER BY uf.filename ASC", [':uid' => $account->id()]);
     $behavior = 0;
     foreach ($file_downloads as $file_download) {
         // Store a flat array so we can array_diff the ones already allowed when
         // building the list of which can be attached.
         $downloadable_files[$file_download->fid] = $file_download->filename;
         $form['file']['download']['file_download'][$file_download->fid] = array('fuid' => array('#type' => 'value', '#value' => $file_download->fuid), 'expiration' => array('#type' => 'value', '#value' => $file_download->expiration), 'remove' => array('#type' => 'checkbox'), 'filename' => array('#markup' => $file_download->filename), 'expires' => array('#markup' => $file_download->expiration ? \Drupal::service('date.formatter')->format($file_download->expiration, 'short') : $this->t('Never')), 'time_polarity' => array('#type' => 'select', '#default_value' => '+', '#options' => array('+' => '+', '-' => '-')), 'time_quantity' => array('#type' => 'textfield', '#size' => 2, '#maxlength' => 2), 'time_granularity' => array('#type' => 'select', '#default_value' => 'day', '#options' => array('never' => $this->t('never'), 'day' => $this->t('day(s)'), 'week' => $this->t('week(s)'), 'month' => $this->t('month(s)'), 'year' => $this->t('year(s)'))), 'downloads_in' => array('#markup' => $file_download->accessed), 'download_limit' => array('#type' => 'textfield', '#maxlength' => 3, '#size' => 3, '#default_value' => $file_download->download_limit ? $file_download->download_limit : NULL), 'addresses_in' => array('#markup' => count(unserialize($file_download->addresses))), 'address_limit' => array('#type' => 'textfield', '#maxlength' => 2, '#size' => 2, '#default_value' => $file_download->address_limit ? $file_download->address_limit : NULL));
         // Incrementally add behaviors.
         _uc_file_download_table_behavior($behavior++, $file_download->fid);
         // Store old values for comparing to see if we actually made any changes.
         $less_reading =& $form['file']['download']['file_download'][$file_download->fid];
         $less_reading['download_limit_old'] = array('#type' => 'value', '#value' => $less_reading['download_limit']['#default_value']);
         $less_reading['address_limit_old'] = array('#type' => 'value', '#value' => $less_reading['address_limit']['#default_value']);
         $less_reading['expiration_old'] = array('#type' => 'value', '#value' => $less_reading['expiration']['#value']);
     }
     // Create the list of files able to be attached to this user.
     $available_files = array();
     $files = db_query("SELECT * FROM {uc_files} ORDER BY filename ASC");
     foreach ($files as $file) {
         if (substr($file->filename, -1) != '/' && substr($file->filename, -1) != '\\') {
             $available_files[$file->fid] = $file->filename;
         }
     }
     // Dialog for uploading new files.
     $available_files = array_diff($available_files, $downloadable_files);
     if (count($available_files)) {
         $form['file']['file_add'] = array('#type' => 'select', '#multiple' => TRUE, '#size' => 6, '#title' => $this->t('Add file'), '#description' => $this->t('Select a file to add as a download. Newly added files will inherit the settings at the :url.', [':url' => Link::createFromRoute($this->t('Ubercart product settings page'), 'uc_product.settings')->toString()]), '#options' => $available_files, '#tree' => TRUE);
     }
     $form['file']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save'));
     return $form;
 }
Example #16
0
 /**
  * Helper function to determine protected forms for an entity.
  *
  * @param $type
  *   The type of entity to check.
  * @param $bundle
  *   An array of bundle names to check.
  *
  * @return array
  *   An array of protected bundles for this entity type.
  */
 public static function _mollom_get_entity_forms_protected($type, $bundles = array())
 {
     // Find out if this entity bundle is protected.
     $protected =& drupal_static(__FUNCTION__, array());
     if (empty($bundles)) {
         $info = entity_get_info($type);
         $bundles = array_keys($info['bundles']);
     }
     $protected_bundles = array();
     foreach ($bundles as $bundle) {
         if (!isset($protected[$type][$bundle])) {
             $protected[$type][$bundle] = db_query_range('SELECT 1 FROM {mollom_form} WHERE entity = :entity AND bundle = :bundle', 0, 1, array(':entity' => $type, ':bundle' => isset($bundle) ? $bundle : $type))->fetchField();
         }
         if (!empty($protected[$type][$bundle])) {
             $protected_bundles[] = $bundle;
         }
     }
     return $protected_bundles;
 }
 /**
  * Writes a log messages and retrieves it via the REST API.
  */
 public function testWatchdog()
 {
     // Write a log message to the DB.
     watchdog('rest', 'Test message');
     // Get the ID of the written message.
     $id = db_query_range("SELECT wid FROM {watchdog} WHERE type = :type ORDER BY wid DESC", 0, 1, array(':type' => 'rest'))->fetchField();
     // Create a user account that has the required permissions to read
     // the watchdog resource via the REST API.
     $account = $this->drupalCreateUser(array('restful get dblog'));
     $this->drupalLogin($account);
     $response = $this->httpRequest("dblog/{$id}", 'GET', NULL, $this->defaultMimeType);
     $this->assertResponse(200);
     $this->assertHeader('content-type', $this->defaultMimeType);
     $log = Json::decode($response);
     $this->assertEqual($log['wid'], $id, 'Log ID is correct.');
     $this->assertEqual($log['type'], 'rest', 'Type of log message is correct.');
     $this->assertEqual($log['message'], 'Test message', 'Log message text is correct.');
     // Request an unknown log entry.
     $response = $this->httpRequest("dblog/9999", 'GET', NULL, $this->defaultMimeType);
     $this->assertResponse(404);
     $decoded = Json::decode($response);
     $this->assertEqual($decoded['error'], 'Log entry with ID 9999 was not found', 'Response message is correct.');
 }
Example #18
0
function filedepot_dispatcher($action)
{
    global $user;
    $filedepot = filedepot_filedepot();
    $nexcloud = filedepot_nexcloud();
    module_load_include('php', 'filedepot', 'lib-theme');
    module_load_include('php', 'filedepot', 'lib-ajaxserver');
    module_load_include('php', 'filedepot', 'lib-common');
    if (function_exists('timer_start')) {
        timer_start('filedepot_timer');
    }
    firelogmsg("AJAX Server code executing - action: {$action}");
    switch ($action) {
        case 'archive':
            if (isset($_GET['checked_files']) && isset($_GET['checked_folders'])) {
                module_load_include('php', 'filedepot', 'filedepot_archiver.class');
                $checked_files = json_decode($_GET['checked_files'], TRUE);
                $checked_folders = json_decode($_GET['checked_folders'], TRUE);
                //print_r($checked_files);
                //die(1);
                $fa = new filedepot_archiver();
                $fa->createAndCleanArchiveDirectory();
                $fa->addCheckedObjectArrays($checked_files, $checked_folders);
                $fa->createArchive();
                $fa->close();
                $fa->download();
                return;
            } else {
                echo "Invalid Parameters";
                return;
            }
            break;
        case 'getfilelisting':
            $cid = intval($_POST['cid']);
            if ($cid > 0) {
                if (db_query("SELECT count(*) FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid))->fetchField() == 1) {
                    $filedepot->ajaxBackgroundMode = TRUE;
                }
            }
            $reportmode = check_plain($_POST['reportmode']);
            $filedepot->activeview = $reportmode;
            $filedepot->cid = $cid;
            ctools_include('object-cache');
            $cache = ctools_object_cache_set('filedepot', 'folder', $cid);
            $data = filedepotAjaxServer_getfilelisting();
            break;
        case 'getfolderlisting':
            $filedepot->ajaxBackgroundMode = TRUE;
            $cid = intval($_POST['cid']);
            $reportmode = check_plain($_POST['reportmode']);
            if ($cid > 0) {
                ctools_include('object-cache');
                $cache = ctools_object_cache_set('filedepot', 'folder', $cid);
                $filedepot->cid = $cid;
                $filedepot->activeview = $reportmode;
                $data = filedepotAjaxServer_getfilelisting();
                firelogmsg("Completed generating FileListing");
            } else {
                $data = array('retcode' => 500);
            }
            break;
        case 'getleftnavigation':
            $data = filedepotAjaxServer_generateLeftSideNavigation();
            break;
        case 'getmorefiledata':
            /** Need to use XML instead of JSON format for return data.
             * It's taking up to 1500ms to interpret (eval) the JSON data into an object in the client code
             * Parsing the XML is about 10ms
             */
            $cid = intval($_POST['cid']);
            $level = intval($_POST['level']);
            $foldernumber = check_plain($_POST['foldernumber']);
            $filedepot->activeview = 'getmoredata';
            $filedepot->cid = $cid;
            $filedepot->lastRenderedFolder = $cid;
            $retval = '<result>';
            $retval .= '<retcode>200</retcode>';
            $retval .= '<displayhtml>' . htmlspecialchars(nexdocsrv_generateFileListing($cid, $level, $foldernumber), ENT_QUOTES, 'utf-8') . '</displayhtml>';
            $retval .= '</result>';
            firelogmsg("Completed generating AJAX return data - cid: {$cid}");
            break;
        case 'getmorefolderdata':
            /* Need to use XML instead of JSON format for return data.
               It's taking up to 1500ms to interpret (eval) the JSON data into an object in the client code
               Parsing the XML is about 10ms
               */
            $cid = intval($_POST['cid']);
            $level = intval($_POST['level']);
            // Need to remove the last part of the passed in foldernumber as it's the incremental file number
            // Which we recalculate in template_preprocess_filelisting()
            $x = explode('.', check_plain($_POST['foldernumber']));
            $x2 = array_pop($x);
            $foldernumber = implode('.', $x);
            $filedepot->activeview = 'getmorefolderdata';
            $filedepot->cid = $cid;
            $filedepot->lastRenderedFolder = $cid;
            $retval = '<result>';
            $retval .= '<retcode>200</retcode>';
            $retval .= '<displayhtml>' . htmlspecialchars(nexdocsrv_generateFileListing($cid, $level, $foldernumber), ENT_QUOTES, 'utf-8') . '</displayhtml>';
            $retval .= '</result>';
            firelogmsg("Completed generating AJAX return data - cid: {$cid}");
            break;
        case 'rendernewfilefolderoptions':
            $cid = intval($_POST['cid']);
            $data['displayhtml'] = theme('filedepot_newfiledialog_folderoptions', array('cid' => $cid));
            break;
        case 'rendernewfolderform':
            $cid = intval($_POST['cid']);
            $data['displayhtml'] = theme('filedepot_newfolderdialog', array('cid' => $cid));
            break;
        case 'createfolder':
            $node = (object) array('uid' => $user->uid, 'name' => $user->name, 'type' => 'filedepot_folder', 'title' => $_POST['catname'], 'parentfolder' => intval($_POST['catparent']), 'folderdesc' => $_POST['catdesc'], 'inherit' => intval($_POST['catinherit']));
            if ($node->parentfolder == 0 and !user_access('administer filedepot')) {
                $data['errmsg'] = t('Error creating Folder - invalid parent folder');
                $data['retcode'] = 500;
            } else {
                node_save($node);
                if ($node->nid) {
                    $data['displaycid'] = $filedepot->cid;
                    $data['retcode'] = 200;
                } else {
                    $data['errmsg'] = t('Error creating Folder');
                    $data['retcode'] = 500;
                }
            }
            break;
        case 'deletefolder':
            $data = array();
            $cid = intval($_POST['cid']);
            $token = isset($_POST['token']) ? $_POST['token'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) {
                $data['retcode'] = 403;
                // Forbidden
            } else {
                $query = db_query("SELECT cid,pid,nid FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid));
                $A = $query->fetchAssoc();
                if ($cid > 0 and $A['cid'] = $cid) {
                    if ($filedepot->checkPermission($cid, 'admin')) {
                        node_delete($A['nid']);
                        $filedepot->cid = $A['pid'];
                        // Set the new active directory to the parent folder
                        $data['retcode'] = 200;
                        $data['activefolder'] = theme('filedepot_activefolder');
                        $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid);
                        $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                    } else {
                        $data['retcode'] = 403;
                        // Forbidden
                    }
                } else {
                    $data['retcode'] = 404;
                    // Not Found
                }
            }
            break;
        case 'updatefolder':
            $token = isset($_POST['token']) ? $_POST['token'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) {
                $data['retcode'] = 403;
                // Forbidden
            } else {
                $data = filedepotAjaxServer_updateFolder();
            }
            break;
        case 'setfolderorder':
            $cid = intval($_POST['cid']);
            $filedepot->cid = intval($_POST['listingcid']);
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // Forbidden
            } else {
                if ($filedepot->checkPermission($cid, 'admin')) {
                    // Check and see if any subfolders don't yet have a order value - if so correct
                    $maxorder = 0;
                    $pid = db_query("SELECT pid FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid))->fetchField();
                    $maxquery = db_query_range("SELECT folderorder FROM {filedepot_categories} WHERE pid=:pid ORDER BY folderorder ASC", 0, 1, array(':pid' => $pid))->fetchField();
                    $next_folderorder = $maxorder + 10;
                    $query = db_query("SELECT cid FROM {filedepot_categories} WHERE pid=:pid AND folderorder = 0", array(':pid' => $pid));
                    while ($B = $query->fetchAssoc()) {
                        db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $next_folderorder, ':cid' => $B['cid']));
                        $next_folderorder += 10;
                    }
                    $itemquery = db_query("SELECT * FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid));
                    $retval = 0;
                    while ($A = $itemquery->fetchAssoc()) {
                        if ($_POST['direction'] == 'down') {
                            $sql = "SELECT folderorder FROM {filedepot_categories} WHERE pid=:pid ";
                            $sql .= "AND folderorder > :folderorder ORDER BY folderorder ASC ";
                            $nextorder = db_query_range($sql, 0, 1, array(':pid' => $A['pid'], ':folderorder' => $A['folderorder']))->fetchField();
                            if ($nextorder > $A['folderorder']) {
                                $folderorder = $nextorder + 5;
                            } else {
                                $folderorder = $A['folderorder'];
                            }
                            db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $folderorder, ':cid' => $cid));
                        } elseif ($_POST['direction'] == 'up') {
                            $sql = "SELECT folderorder FROM {filedepot_categories} WHERE pid=:pid ";
                            $sql .= "AND folderorder < :folderorder ORDER BY folderorder DESC ";
                            $nextorder = db_query_range($sql, 0, 1, array(':pid' => $A['pid'], ':folderorder' => $A['folderorder']))->fetchField();
                            $folderorder = $nextorder - 5;
                            if ($folderorder <= 0) {
                                $folderorder = 0;
                            }
                            db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $folderorder, ':cid' => $cid));
                        }
                    }
                    /* Re-order any folders that may have just been moved */
                    $query = db_query("SELECT cid,folderorder from {filedepot_categories} WHERE pid=:pid ORDER BY folderorder", array(':pid' => $pid));
                    $folderorder = 10;
                    $stepnumber = 10;
                    while ($A = $query->fetchAssoc()) {
                        if ($folderorder != $A['folderOrder']) {
                            db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $folderorder, ':cid' => $A['cid']));
                        }
                        $folderorder += $stepnumber;
                    }
                    $data['retcode'] = 200;
                    $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid);
                } else {
                    $data['retcode'] = 400;
                }
            }
            break;
        case 'updatefoldersettings':
            $cid = intval($_POST['cid']);
            $notifyadd = intval($_POST['fileadded_notify']);
            $notifychange = intval($_POST['filechanged_notify']);
            if ($user->uid > 0 and $cid >= 1) {
                // Update the personal folder notifications for user
                if (db_query("SELECT count(*) FROM {filedepot_notifications} WHERE cid=:cid AND uid=:uid", array(':cid' => $cid, ':uid' => $user->uid))->fetchField() == 0) {
                    $sql = "INSERT INTO {filedepot_notifications} (cid,cid_newfiles,cid_changes,uid,date) ";
                    $sql .= "VALUES (:cid,:notifyadd,:notifychange,:uid,:time)";
                    db_query($sql, array(':cid' => $cid, ':notifyadd' => $notifyadd, ':notifychange' => $notifychange, ':uid' => $user->uid, ':time' => time()));
                } else {
                    $sql = "UPDATE {filedepot_notifications} set cid_newfiles=:notifyadd, ";
                    $sql .= "cid_changes=:notifychange, date=:time ";
                    $sql .= "WHERE uid=:uid and cid=:cid";
                    db_query($sql, array(':notifyadd' => $notifyadd, ':notifychange' => $notifychange, ':time' => time(), ':uid' => $user->uid, ':cid' => $cid));
                }
                $data['retcode'] = 200;
                $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid);
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'loadfiledetails':
            $data = filedepotAjaxServer_loadFileDetails();
            break;
        case 'refreshfiledetails':
            $reportmode = check_plain($_POST['reportmode']);
            $fid = intval($_POST['id']);
            $cid = db_query("SELECT cid FROM {filedepot_files} WHERE fid=:fid", array(':fid' => $fid))->fetchField();
            if ($filedepot->checkPermission($cid, 'view')) {
                $data['retcode'] = 200;
                $data['fid'] = $fid;
                $data['displayhtml'] = theme('filedepot_filedetail', array('fid' => $fid, 'reportmode' => $reportmode));
            } else {
                $data['retcode'] = 400;
                $data['error'] = t('Invalid access');
            }
            break;
        case 'updatenote':
            $fid = intval($_POST['fid']);
            $version = intval($_POST['version']);
            $note = check_plain($_POST['note']);
            $reportmode = check_plain($_POST['reportmode']);
            $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($fid > 0) {
                db_query("UPDATE {filedepot_fileversions} SET notes=:notes WHERE fid=:fid and version=:version", array(':notes' => $note, ':fid' => $fid, ':version' => $version));
                $data['retcode'] = 200;
                $data['fid'] = $fid;
                $data['displayhtml'] = theme('filedepot_filedetail', array('fid' => $fid, 'reportmode' => $reportmode));
            } else {
                $data['retcode'] = 400;
            }
            break;
        case 'getfolderperms':
            $cid = intval($_POST['cid']);
            if ($cid > 0) {
                if ($filedepot->ogenabled) {
                    $data['html'] = theme('filedepot_folderperms_ogenabled', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS)));
                } else {
                    $data['html'] = theme('filedepot_folderperms', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS)));
                }
                $data['retcode'] = 200;
            } else {
                $data['retcode'] = 404;
            }
            break;
        case 'delfolderperms':
            $id = intval($_POST['id']);
            $token = isset($_POST['token']) ? $_POST['token'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERPERMS)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($id > 0) {
                $query = db_query("SELECT catid, permtype, permid FROM  {filedepot_access} WHERE accid=:accid", array(':accid' => $id));
                $A = $query->fetchAssoc();
                if ($filedepot->checkPermission($A['catid'], 'admin')) {
                    db_delete('filedepot_access')->condition('accid', $id)->execute();
                    db_update('filedepot_usersettings')->fields(array('allowable_view_folders' => ''))->execute();
                    // For this folder - I need to update the access metrics now that a permission has been removed
                    $nexcloud->update_accessmetrics($A['catid']);
                    if ($filedepot->ogenabled) {
                        $data['html'] = theme('filedepot_folderperms_ogenabled', array('cid' => $A['catid'], 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS)));
                    } else {
                        $data['html'] = theme('filedepot_folderperms', array('cid' => $A['catid'], 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS)));
                    }
                    $data['retcode'] = 200;
                } else {
                    $data['retcode'] = 403;
                    // Forbidden
                }
            } else {
                $data['retcode'] = 404;
                // Not Found
            }
            break;
        case 'addfolderperm':
            $cid = intval($_POST['catid']);
            $token = isset($_POST['token']) ? $_POST['token'] : NULL;
            if (!isset($_POST['cb_access'])) {
                $data['retcode'] = 204;
                // No permission options selected - return 'No content' statuscode
            } elseif ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERPERMS)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($filedepot->updatePerms($cid, $_POST['cb_access'], $_POST['selusers'], $_POST['selgroups'], $_POST['selroles'])) {
                if (is_array($_POST['selroles']) and count($_POST['selroles']) > 0) {
                    foreach ($_POST['selroles'] as $roleid) {
                        $roleid = intval($roleid);
                        if ($roleid > 0) {
                            $nexcloud->update_accessmetrics($cid);
                        }
                    }
                }
                if ($filedepot->ogenabled) {
                    if (is_array($_POST['selgroups']) and count($_POST['selgroups']) > 0) {
                        foreach ($_POST['selgroups'] as $groupid) {
                            $groupid = intval($groupid);
                            if ($groupid > 0) {
                                $nexcloud->update_accessmetrics($cid);
                            }
                        }
                    }
                    $data['html'] = theme('filedepot_folderperms_ogenabled', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS)));
                } else {
                    $data['html'] = theme('filedepot_folderperms', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS)));
                }
                $data['retcode'] = 200;
            } else {
                $data['retcode'] = 403;
                // Forbidden
            }
            break;
        case 'updatefile':
            $fid = intval($_POST['id']);
            $folder_id = intval($_POST['folder']);
            $version = intval($_POST['version']);
            $filetitle = $_POST['filetitle'];
            $description = $_POST['description'];
            $vernote = $_POST['version_note'];
            $approved = check_plain($_POST['approved']);
            $tags = $_POST['tags'];
            $data = array();
            $data['tagerror'] = '';
            $data['errmsg'] = '';
            $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                $data['retcode'] = 403;
                // forbidden
                $data['errmsg'] = t('Invalid request');
            } elseif ($_POST['cid'] == 'incoming' and $fid > 0) {
                $filemoved = FALSE;
                $sql = "UPDATE {filedepot_import_queue} SET orig_filename=:filename, description=:description,";
                $sql .= "version_note=:notes WHERE id=:fid";
                db_query($sql, array(':filename' => $filetitle, ':description' => $description, ':notes' => $vernote, ':fid' => $fid));
                $data['retcode'] = 200;
                if ($folder_id > 0 and $filedepot->moveIncomingFile($fid, $folder_id)) {
                    $filemoved = TRUE;
                    $filedepot->activeview = 'incoming';
                    $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                    $data['displayhtml'] = filedepot_displayFolderListing();
                }
            } elseif ($fid > 0) {
                $filemoved = FALSE;
                if ($approved == 0) {
                    $sql = "UPDATE {filedepot_filesubmissions} SET title=:title, description=:description,";
                    $sql .= "version_note=:notes, cid=:cid, tags=:tags WHERE id=:fid;";
                    db_query($sql, array(':title' => $filetitle, ':description' => $description, ':notes' => $vernote, ':cid' => $folder_id, ':tags' => $tags, ':fid' => $fid));
                    $data['cid'] = $folder_id;
                    $data['tags'] = '';
                } else {
                    $query = db_query("SELECT fname,cid,version,submitter FROM {filedepot_files} WHERE fid=:fid", array(':fid' => $fid));
                    list($fname, $cid, $current_version, $submitter) = array_values($query->fetchAssoc());
                    // Allow updating the category, title, description and image for the current version and primary file record
                    if ($version == $current_version) {
                        db_query("UPDATE {filedepot_files} SET title=:title,description=:desc,date=:time WHERE fid=:fid", array(':title' => $filetitle, ':desc' => $description, ':time' => time(), ':fid' => $fid));
                        // Test if user has selected a different directory and if they have perms then move else return FALSE;
                        if ($folder_id > 0) {
                            $newcid = $folder_id;
                            if ($cid != $newcid) {
                                $filemoved = $filedepot->moveFile($fid, $newcid);
                                if ($filemoved == FALSE) {
                                    $data['errmsg'] = t('Error moving file');
                                }
                            }
                            $data['cid'] = $newcid;
                        } else {
                            $data['cid'] = $cid;
                        }
                        unset($_POST['tags']);
                        // Format tags will check this to format tags in case we are doing a search which we are not in this case.
                        $data['tags'] = filedepot_formatfiletags($tags);
                    }
                    db_query("UPDATE {filedepot_fileversions} SET notes=:notes WHERE fid=:fid and version=:version", array(':notes' => $vernote, ':fid' => $fid, ':version' => $version));
                    // Update the file tags if role or group permission set -- we don't support tag access perms at the user level.
                    if ($filedepot->checkPermission($folder_id, 'view', 0, FALSE)) {
                        if ($filedepot->checkPermission($folder_id, 'admin', 0, FALSE) or $user->uid == $submitter) {
                            $admin = TRUE;
                        } else {
                            $admin = FALSE;
                        }
                        if (!$nexcloud->update_tags($fid, $tags, $admin)) {
                            $data['tagerror'] = t('Tags not added - Group or Role assigned view perms required');
                            $data['tags'] = '';
                        }
                    } else {
                        $data['tagerror'] = t('Problem adding or updating tags');
                        $data['tags'] = '';
                    }
                }
                $data['retcode'] = 200;
                $data['tagcloud'] = theme('filedepot_tagcloud');
            } else {
                $data['retcode'] = 500;
                $data['errmsg'] = t('Invalid File');
            }
            $data['description'] = nl2br(filter_xss($description));
            $data['fid'] = $fid;
            $data['filename'] = filter_xss($filetitle);
            $data['filemoved'] = $filemoved;
            break;
        case 'deletefile':
            $fid = intval($_POST['fid']);
            $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0 and $fid > 0) {
                $data = filedepotAjaxServer_deleteFile($fid);
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'deletecheckedfiles':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $data = filedepotAjaxServer_deleteCheckedFiles();
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'deleteversion':
            $fid = intval($_POST['fid']);
            $version = intval($_POST['version']);
            $reportmode = check_plain($_POST['reportmode']);
            $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($fid > 0 and $version > 0) {
                if ($filedepot->deleteVersion($fid, $version)) {
                    $data['retcode'] = 200;
                    $data['fid'] = $fid;
                    $data['displayhtml'] = theme('filedepot_filedetail', array('fid' => $fid, 'reportmode' => $reportmode));
                } else {
                    $data['retcode'] = 400;
                }
            } else {
                $data['retcode'] = 400;
            }
            break;
        case 'togglefavorite':
            $id = intval($_POST['id']);
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0 and $id >= 1) {
                if (db_query("SELECT count(fid) FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id))->fetchField() > 0) {
                    $data['favimgsrc'] = base_path() . drupal_get_path('module', 'filedepot') . '/css/images/' . $filedepot->getFileIcon('favorite-off');
                    db_query("DELETE FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id));
                } else {
                    $data['favimgsrc'] = base_path() . drupal_get_path('module', 'filedepot') . '/css/images/' . $filedepot->getFileIcon('favorite-on');
                    db_query("INSERT INTO {filedepot_favorites} (uid,fid) VALUES (:uid,:fid)", array(':uid' => $user->uid, ':fid' => $id));
                }
                $data['retcode'] = 200;
            } else {
                $data['retcode'] = 400;
            }
            break;
        case 'markfavorite':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $cid = intval($_POST['cid']);
                $reportmode = check_plain($_POST['reportmode']);
                $fileitems = check_plain($_POST['checkeditems']);
                $files = explode(',', $fileitems);
                $filedepot->cid = $cid;
                $filedepot->activeview = $reportmode;
                foreach ($files as $id) {
                    if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id))->fetchField() == 0) {
                        db_query("INSERT INTO {filedepot_favorites} (uid,fid) VALUES (:uid,:fid)", array(':uid' => $user->uid, 'fid' => $id));
                    }
                }
                $data['retcode'] = 200;
                $data['displayhtml'] = filedepot_displayFolderListing($cid);
            }
            break;
        case 'clearfavorite':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $cid = intval($_POST['cid']);
                $reportmode = check_plain($_POST['reportmode']);
                $fileitems = check_plain($_POST['checkeditems']);
                $files = explode(',', $fileitems);
                $filedepot->cid = $cid;
                $filedepot->activeview = $reportmode;
                foreach ($files as $id) {
                    if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id))->fetchField() == 1) {
                        db_query("DELETE FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id));
                    }
                }
                $data['retcode'] = 200;
                $data['displayhtml'] = filedepot_displayFolderListing($cid);
            }
            break;
        case 'togglelock':
            $fid = intval($_POST['fid']);
            $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                $data['error'] = t('Error locking file');
            } else {
                $data['error'] = '';
                $data['fid'] = $fid;
                $query = db_query("SELECT status FROM {filedepot_files} WHERE fid=:fid", array(':fid' => $fid));
                if ($query) {
                    list($status) = array_values($query->fetchAssoc());
                    if ($status == 1) {
                        db_query("UPDATE {filedepot_files} SET status='2', status_changedby_uid=:uid WHERE fid=:fid", array(':uid' => $user->uid, ':fid' => $fid));
                        $stat_user = db_query("SELECT name FROM {users} WHERE uid=:uid", array(':uid' => $user->uid))->fetchField();
                        $data['message'] = 'File Locked successfully';
                        $data['locked_message'] = '* ' . t('Locked by %name', array('%name' => $stat_user));
                        $data['locked'] = TRUE;
                    } else {
                        db_query("UPDATE {filedepot_files} SET status='1', status_changedby_uid=:uid WHERE fid=:fid", array(':uid' => $user->uid, ':fid' => $fid));
                        $data['message'] = 'File Un-Locked successfully';
                        $data['locked'] = FALSE;
                    }
                } else {
                    $data['error'] = t('Error locking file');
                }
            }
            break;
        case 'movecheckedfiles':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $data = filedepotAjaxServer_moveCheckedFiles();
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'rendermoveform':
            $data['displayhtml'] = theme('filedepot_movefiles_form');
            break;
        case 'rendermoveincoming':
            $data['displayhtml'] = theme('filedepot_moveincoming_form');
            break;
        case 'togglesubscribe':
            $fid = intval($_POST['fid']);
            $cid = intval($_POST['cid']);
            $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                $data['error'] = t('Error subscribing');
            } else {
                global $base_url;
                $data['error'] = '';
                $data['fid'] = $fid;
                $ret = filedepotAjaxServer_updateFileSubscription($fid, 'toggle');
                // @TODO: Notifyicon does not appear to be implemented
                if ($ret['retcode'] === TRUE) {
                    $data['retcode'] = 200;
                    if ($ret['subscribed'] === TRUE) {
                        $data['subscribed'] = TRUE;
                        $data['message'] = 'You will be notified of any new versions of this file';
                        $path = drupal_get_path('module', 'filedepot') . '/css/images/email-green.gif';
                        $data['notifyicon'] = $base_url . '/' . $path;
                        $data['notifymsg'] = 'Notification Enabled - Click to change';
                    } elseif ($ret['subscribed'] === FALSE) {
                        $data['subscribed'] = FALSE;
                        $data['message'] = 'You will not be notified of any new versions of this file';
                        $path = drupal_get_path('module', 'filedepot') . '/css/images/email-regular.gif';
                        $data['notifyicon'] = $base_url . '/' . $path;
                        $data['notifymsg'] = 'Notification Disabled - Click to change';
                    }
                } else {
                    $data['error'] = t('Error accessing file record');
                    $data['retcode'] = 404;
                }
            }
            break;
        case 'updatenotificationsettings':
            if ($user->uid > 0) {
                if (db_query("SELECT count(uid) FROM {filedepot_usersettings} WHERE uid=:uid", array(':uid' => $user->uid))->fetchField() == 0) {
                    db_query("INSERT INTO {filedepot_usersettings} (uid) VALUES ( :uid )", array(':uid' => $user->uid));
                }
                $sql = "UPDATE {filedepot_usersettings} SET notify_newfile=:newfile,notify_changedfile=:changefile,allow_broadcasts=:broadcast WHERE uid=:uid";
                db_query($sql, array(':newfile' => $_POST['fileadded_notify'], ':changefile' => $_POST['fileupdated_notify'], ':broadcast' => $_POST['admin_broadcasts'], ':uid' => $user->uid));
                $data['retcode'] = 200;
                $data['displayhtml'] = theme('filedepot_notifications');
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'deletenotification':
            $id = intval($_POST['id']);
            if ($user->uid > 0 and $id > 0) {
                db_query("DELETE FROM {filedepot_notifications} WHERE id=:id AND uid=:uid", array(':id' => $id, ':uid' => $user->uid));
                $data['retcode'] = 200;
                $data['displayhtml'] = theme('filedepot_notifications');
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'clearnotificationlog':
            db_query("DELETE FROM {filedepot_notificationlog} WHERE target_uid=:uid", array(':uid' => $user->uid));
            $data['retcode'] = 200;
            break;
        case 'multisubscribe':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $reportmode = check_plain($_POST['reportmode']);
                $fileitems = check_plain($_POST['checkeditems']);
                $folderitems = check_plain($_POST['checkedfolders']);
                $filedepot->cid = intval($_POST['cid']);
                $filedepot->activeview = check_plain($_POST['reportmode']);
                if (!empty($fileitems)) {
                    $files = explode(',', $fileitems);
                    foreach ($files as $fid) {
                        filedepotAjaxServer_updateFileSubscription($fid, 'add');
                    }
                }
                if (!empty($folderitems)) {
                    $folders = explode(',', $folderitems);
                    foreach ($folders as $cid) {
                        if (db_query("SELECT count(id) FROM {filedepot_notifications} WHERE cid=:cid AND uid=:uid", array(':cid' => $cid, ':uid' => $user->uid))->fetchField() == 0) {
                            $sql = "INSERT INTO {filedepot_notifications} (cid,cid_newfiles,cid_changes,uid,date) ";
                            $sql .= "VALUES (:cid,1,1,:uid,:time)";
                            db_query($sql, array(':cid' => $cid, ':uid' => $user->uid, ':time' => time()));
                        }
                    }
                }
                $data['retcode'] = 200;
                $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid);
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'autocompletetag':
            $matches = $nexcloud->get_matchingtags($_GET['query']);
            $retval = implode("\n", $matches);
            break;
        case 'refreshtagcloud':
            $data['retcode'] = 200;
            $data['tagcloud'] = theme('filedepot_tagcloud');
            break;
        case 'search':
            $query = $_POST['query'];
            if (!empty($query)) {
                $filedepot->activeview = 'search';
                $filedepot->cid = 0;
                $data['retcode'] = 200;
                $data['displayhtml'] = filedepot_displaySearchListing($query);
                $data['header'] = theme('filedepot_header');
                $data['activefolder'] = theme('filedepot_activefolder');
            } else {
                $data['retcode'] = 400;
            }
            break;
        case 'searchtags':
            if (isset($_POST['tags'])) {
                $tags = stripslashes($_POST['tags']);
            } else {
                $tags = '';
            }
            if (isset($_POST['removetag'])) {
                $removetag = stripslashes($_POST['removetag']);
            } else {
                $removetag = '';
            }
            $current_search_tags = '';
            $filedepot->activeview = 'searchtags';
            $filedepot->cid = 0;
            if (!empty($tags)) {
                if (!empty($removetag)) {
                    $removetag = stripslashes($removetag);
                    $atags = explode(',', $tags);
                    $key = array_search($removetag, $atags);
                    if ($key !== FALSE) {
                        unset($atags[$key]);
                    }
                    $tags = implode(',', $atags);
                    $_POST['tags'] = $tags;
                } else {
                    $removetag = '';
                }
                if (!empty($tags)) {
                    $data['searchtags'] = stripslashes($tags);
                    $atags = explode(',', $tags);
                    if (count($atags) >= 1) {
                        foreach ($atags as $tag) {
                            $tag = trim($tag);
                            // added to handle extra space thats added when removing a tag - thats between 2 other tags
                            if (!empty($tag)) {
                                $current_search_tags .= theme('filedepot_searchtag', array('searchtag' => addslashes($tag), 'label' => check_plain($tag)));
                            }
                        }
                    }
                    $data['retcode'] = 200;
                    $data['currentsearchtags'] = $current_search_tags;
                    $data['displayhtml'] = filedepot_displayTagSearchListing($tags);
                    $data['tagcloud'] = theme('filedepot_tagcloud');
                    $data['header'] = theme('filedepot_header');
                    $data['activefolder'] = theme('filedepot_activefolder');
                } else {
                    unset($_POST['tags']);
                    $filedepot->activeview = 'latestfiles';
                    $data['retcode'] = 200;
                    $data['currentsearchtags'] = '';
                    $data['tagcloud'] = theme('filedepot_tagcloud');
                    $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid);
                    $data['header'] = theme('filedepot_header');
                    $data['activefolder'] = theme('filedepot_activefolder');
                }
            } else {
                $data['tagcloud'] = theme('filedepot_tagcloud');
                $data['retcode'] = 203;
                // Partial Information
            }
            break;
        case 'approvefile':
            $id = intval($_POST['id']);
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0 and $filedepot->approveFileSubmission($id)) {
                $filedepot->cid = 0;
                $filedepot->activeview = 'approvals';
                $data = filedepotAjaxServer_getfilelisting();
                $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                $data['retcode'] = 200;
            } else {
                $data['retcode'] = 400;
            }
            break;
        case 'approvesubmissions':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $reportmode = check_plain($_POST['reportmode']);
                $fileitems = check_plain($_POST['checkeditems']);
                $files = explode(',', $fileitems);
                $approved_files = 0;
                $filedepot->activeview = 'approvals';
                foreach ($files as $id) {
                    // Check if this is a valid submission record
                    if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField() == 1) {
                        // Verify that user has Admin Access to approve this file
                        $cid = db_query("SELECT cid FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField();
                        if ($cid > 0 and $filedepot->checkPermission($cid, array('admin', 'approval'), 0, FALSE)) {
                            if ($filedepot->approveFileSubmission($id)) {
                                $approved_files++;
                            }
                        }
                    }
                }
                if ($approved_files > 0) {
                    $data['retcode'] = 200;
                    $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                    $data['displayhtml'] = filedepot_displayFolderListing();
                } else {
                    $data['retcode'] = 400;
                }
            }
            break;
        case 'deletesubmissions':
            $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($user->uid > 0) {
                $reportmode = check_plain($_POST['reportmode']);
                $fileitems = check_plain($_POST['checkeditems']);
                $files = explode(',', $fileitems);
                $deleted_files = 0;
                $filedepot->activeview = 'approvals';
                foreach ($files as $id) {
                    // Check if this is a valid submission record
                    if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField() == 1) {
                        // Verify that user has Admin Access to approve this file
                        $cid = db_query("SELECT cid FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField();
                        if ($cid > 0 and $filedepot->checkPermission($cid, array('admin', 'approval'), 0, FALSE)) {
                            if ($filedepot->deleteSubmission($id)) {
                                $deleted_files++;
                            }
                        }
                    }
                }
                if ($deleted_files > 0) {
                    $data['retcode'] = 200;
                    $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                    $data['displayhtml'] = filedepot_displayFolderListing();
                } else {
                    $data['retcode'] = 400;
                }
            }
            break;
        case 'deleteincomingfile':
            $id = intval($_POST['id']);
            $message = '';
            $token = isset($_POST['token']) ? $_POST['token'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) {
                $data['retcode'] = 403;
                // forbidden
            } else {
                $fid = db_query("SELECT drupal_fid FROM {filedepot_import_queue} WHERE id=:id", array(':id' => $id))->fetchField();
                if ($fid > 0) {
                    $filepath = db_query("SELECT filepath FROM {files} WHERE fid=:fid", array(':fid' => $fid))->fetchField();
                    if (!empty($filepath) and file_exists($filepath)) {
                        @unlink($filepath);
                    }
                    db_query("DELETE FROM {files} WHERE fid=:fid", array(':fid' => $fid));
                    db_query("DELETE FROM {filedepot_import_queue} WHERE id=:id", array(':id' => $id));
                    $data['retcode'] = 200;
                    $filedepot->activeview = 'incoming';
                    $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                    $data['displayhtml'] = filedepot_displayFolderListing();
                } else {
                    $data['retcode'] = 500;
                }
                $retval = json_encode($data);
            }
            break;
        case 'moveincomingfile':
            //FILEDEPOT_TOKEN_FOLDERMGMT
            $newcid = intval($_POST['newcid']);
            $id = intval($_POST['id']);
            $filedepot->activeview = 'incoming';
            $data = array();
            $token = isset($_POST['token']) ? $_POST['token'] : NULL;
            if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) {
                $data['retcode'] = 403;
                // forbidden
            } elseif ($newcid > 0 and $id > 0 and $filedepot->moveIncomingFile($id, $newcid)) {
                // Send out email notifications of new file added to all users subscribed  -  Get fileid for the new file record
                $fid = db_query("SELECT fid FROM {filedepot_files} WHERE cid=:cid AND submitter=:uid ORDER BY fid DESC", array(':cid' => $newcid, ':uid' => $user->uid), 0, 1)->fetchField();
                filedepot_sendNotification($fid, FILEDEPOT_NOTIFY_NEWFILE);
                $data['retcode'] = 200;
                $data = filedepotAjaxServer_generateLeftSideNavigation($data);
                $data['displayhtml'] = filedepot_displayFolderListing();
            } else {
                $data['retcode'] = 500;
            }
            break;
        case 'broadcastalert':
            $data = array();
            if (variable_get('filedepot_default_allow_broadcasts', 1) == 0) {
                $data['retcode'] = 204;
            } else {
                $fid = intval($_POST['fid']);
                $message = check_plain($_POST['message']);
                $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL;
                if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) {
                    $data['retcode'] = 403;
                } elseif (!empty($message) and $fid > 0) {
                    $data = filedepotAjaxServer_broadcastAlert($fid, $message);
                } else {
                    $data['retcode'] = 500;
                }
            }
            break;
    }
    ob_clean();
    if ($action != 'autocompletetag') {
        if ($action != 'getmorefiledata' and $action != 'getmorefolderdata') {
            $retval = json_encode($data);
        }
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('content-type: application/xml', TRUE);
        echo "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
    }
    echo $retval;
}
Example #19
0
    /**
     * Returns a Zeitgeist statistics object.
     *
     * This is the most important function/feature of the module.
     *
     * @param int $span
     *   One of the predefined Drupal\zeitgeist\Span::* constants
     * @param int $timestamp
     *   A UNIX timestamp within the span. NULL means REQUEST_TIME.
     * @param string $category
     *   Restricts the type of searches taken into account (or not)
     * @param int $count
     *   Limits results to $count results, or does not limit if 0.
     *
     * @return Drupal\zeitgeist\Statistics
     *   The statistics over the chosen time range.
     */
    public static function getStatistics($span = Span::MONTH, $timestamp = NULL, $category = NULL, $count = 0)
    {
        list($ts1, $ts2) = Statistics::getSpanLimits($span, $timestamp);
        $table = static::getTableName();
        $params = array(':tsmin' => $ts1, ':tsmax' => $ts2);
        if (isset($category)) {
            $filter = '  AND (zg.category = :category)';
            $params[':category'] = $category;
        } else {
            $filter = '';
        }
        $sql = <<<SQL
SELECT zg.search, zg.category, count(zg.ts) cnt
FROM {$table} zg
WHERE (zg.ts >= :tsmin) AND (zg.ts < :tsmax)
{$filter}
GROUP BY 1, 2
ORDER BY 3 DESC, 1 ASC, 2 ASC
SQL;
        // No access control on this table.
        $result = $count > 0 ? db_query_range($sql, 0, $count, $params) : db_query($sql, $params);
        $ret = new Statistics($ts1, $ts2);
        $ret->scores = array();
        foreach ($result as $o) {
            $ret->addScore($o->search, $o->category, $o->cnt);
        }
        return $ret;
    }
 /**
  * {@inheritdoc}
  */
 public function checkChangedLink(array $link, $original_link = NULL, $flag = FALSE)
 {
     $changed = FALSE;
     if ($original_link === NULL) {
         // Load only the fields necessary for data to be changed in the sitemap.
         $original_link = db_query_range("SELECT loc, access, status, lastmod, priority, changefreq, changecount, language FROM {xmlsitemap} WHERE type = :type AND id = :id", 0, 1, array(':type' => $link['type'], ':id' => $link['id']))->fetchAssoc();
     }
     if (!$original_link) {
         if ($link['access'] && $link['status']) {
             // Adding a new visible link.
             $changed = TRUE;
         }
     } else {
         if (!($original_link['access'] && $original_link['status']) && $link['access'] && $link['status']) {
             // Changing a non-visible link to a visible link.
             $changed = TRUE;
         } elseif ($original_link['access'] && $original_link['status'] && array_diff_assoc($original_link, $link)) {
             // Changing a visible link
             $changed = TRUE;
         }
     }
     if ($changed && $flag) {
         $this->state->set('xmlsitemap_regenerate_needed', TRUE);
     }
     return $changed;
 }
Example #21
0
 /**
  * Returns the count of the randomly created feed array.
  *
  * @return int
  *   Number of feed items on default feed created by createFeed().
  */
 public function getDefaultFeedItemCount()
 {
     // Our tests are based off of rss.xml, so let's find out how many elements should be related.
     $feed_count = db_query_range('SELECT COUNT(DISTINCT nid) FROM {node_field_data} n WHERE n.promote = 1 AND n.status = 1', 0, $this->config('system.rss')->get('items.limit'))->fetchField();
     return $feed_count > 10 ? 10 : $feed_count;
 }
Example #22
0
 /**
  * Tests the escaping of links in the operation row of a database log detail
  * page.
  */
 private function verifyLinkEscaping()
 {
     $link = \Drupal::l('View', Url::fromRoute('entity.node.canonical', array('node' => 1)));
     $message = 'Log entry added to do the verifyLinkEscaping test.';
     $this->generateLogEntries(1, array('message' => $message, 'link' => $link));
     $result = db_query_range('SELECT wid FROM {watchdog} ORDER BY wid DESC', 0, 1);
     $this->drupalGet('admin/reports/dblog/event/' . $result->fetchField());
     // Check if the link exists (unescaped).
     $this->assertRaw($link);
 }
 /**
  * checks if voc has terms
  *
  * @param $vid voc id
  * @return true, if terms already exists, else false
  */
 public static function _taxonomy_manager_voc_is_empty($vid)
 {
     $has_rows = (bool) db_query_range("SELECT 1 FROM {taxonomy_term_data} t INNER JOIN {taxonomy_term_hierarchy} h ON t.tid = h.tid WHERE vid = :vid AND h.parent = 0", 0, 1, array(':vid' => $vid))->fetchField();
     return !$has_rows;
 }
Example #24
0
function filedepotAjaxServer_moveCheckedFiles()
{
    global $user;
    $filedepot = filedepot_filedepot();
    $message = '';
    $retval = array();
    $cid = intval($_POST['cid']);
    $newcid = intval($_POST['newcid']);
    $reportmode = check_plain($_POST['reportmode']);
    $fileitems = check_plain($_POST['checkeditems']);
    $files = explode(',', $fileitems);
    $filedepot->cid = $cid;
    $filedepot->activeview = $reportmode;
    $movedfiles = 0;
    if ($newcid > 0 and $user->uid > 0) {
        foreach ($files as $id) {
            if ($id > 0) {
                if ($reportmode == 'incoming') {
                    if ($filedepot->moveIncomingFile($id, $newcid)) {
                        $movedfiles++;
                    }
                } else {
                    if ($filedepot->moveFile($id, $newcid)) {
                        $movedfiles++;
                    }
                }
            }
        }
    }
    if ($movedfiles > 0) {
        $message = "Successfully moved {$movedfiles} files to this folder.";
        if ($reportmode == 'incoming') {
            // Send out email notifications of new file added to all users subscribed  -  Get fileid for the new file record
            $args = array(':cid' => $newcid, ':uid' => $user->uid);
            $fid = db_query_range("SELECT fid FROM {filedepot_files} WHERE cid=:cid AND submitter=:uid ORDER BY fid DESC", 0, 1, $args)->fetchField();
            filedepot_sendNotification($fid, FILEDEPOT_NOTIFY_NEWFILE);
        }
        $cid = $newcid;
    } elseif ($newcid == 0) {
        $message = 'Unable to move any files - Invalid new folder selected';
    } else {
        $message = 'Unable to move any files - invalid folder or insufficient rights';
    }
    $retval['retcode'] = 200;
    $retval['cid'] = $cid;
    $retval['movedfiles'] = $movedfiles;
    $retval['message'] = $message;
    $retval['activefolder'] = theme('filedepot_activefolder');
    $retval['displayhtml'] = filedepot_displayFolderListing($cid);
    return $retval;
}
Example #25
0
/**
 * Report the number of times a file is referenced by a module.
 *
 * This hook is called to determine if a files is in use. Multiple modules may
 * be referencing the same file and to prevent one from deleting a file used by
 * another this hook is called.
 *
 * @param $file
 *   The file object being checked for references.
 * @return
 *   If the module uses this file return an array with the module name as the
 *   key and the value the number of times the file is used.
 *
 * @see file_delete()
 * @see upload_file_references()
 */
function hook_file_references($file)
{
    // If upload.module is still using a file, do not let other modules delete it.
    $file_used = (bool) db_query_range('SELECT 1 FROM {upload} WHERE fid = :fid', array(':fid' => $file->fid), 0, 1)->fetchField();
    if ($file_used) {
        // Return the name of the module and how many references it has to the file.
        return array('upload' => $count);
    }
}
Example #26
0
         break;
     case 2:
         // Last in cat
         $cat_lnum = $parent_rnum;
         if ($parent_id == 0) {
             $result = db_query("SELECT max(rnum) AS max FROM categories");
             if (db_num_rows($result)) {
                 $item = db_fetch_array($result);
                 $cat_lnum = $item['max'] + 1;
             }
         }
         break;
     default:
         // Sort
         // Znalezienie największego ale mniejszego elementu od obecnie wstawianego
         $result = db_query_range("\n\t\t\t\t\tSELECT rnum FROM categories\n\t\t\t\t\tWHERE id_parent = {$parent_id} AND lower(name) < lower('" . FrmDb($frm[name]) . "')\n\t\t\t\t\tORDER BY name DESC\n\t\t\t\t\t", 1, 0);
         if (db_num_rows($result)) {
             $item = db_fetch_array($result);
             $cat_lnum = $item['rnum'] + 1;
         } else {
             // Nie znaleziono mniejszych więc jest pierwszy
             $cat_lnum = $parent_lnum + 1;
         }
         break;
 }
 $cat_rnum = $cat_lnum + 1;
 /*
 			echo 
 			'<BR><BR>'.
 			FramedTable1().
 			"Parent :: ID:$parent_id ($parent_lnum,$parent_rnum)<BR>".
Example #27
0
 /**
  * Verify that existing contrib code cannot overwrite immutable form state.
  */
 public function testImmutableFormLegacyProtection()
 {
     $this->drupalGet('form_test/form-storage', ['query' => ['cache' => 1, 'immutable' => 1]]);
     $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
     $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
     $build_id = (string) $build_id_fields[0]['value'];
     // Try to poison the form cache.
     $original = $this->drupalGetAjax('form-test/form-storage-legacy/' . $build_id);
     $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
     $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
     // Assert that a watchdog message was logged by
     // \Drupal::formBuilder()->setCache().
     $status = (bool) db_query_range('SELECT 1 FROM {watchdog} WHERE message = :message', 0, 1, [':message' => 'Form build-id mismatch detected while attempting to store a form in the cache.']);
     $this->assert($status, 'A watchdog message was logged by \\Drupal::formBuilder()->setCache');
     // Ensure that the form state was not poisoned by the preceding call.
     $original = $this->drupalGetAjax('form-test/form-storage-legacy/' . $build_id);
     $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
     $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
     $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
     $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
 }
Example #28
0
/**
 * Update Drupal's full-text index for this module.
 *
 * Modules can implement this hook if they want to use the full-text indexing
 * mechanism in Drupal.
 *
 * This hook is called every cron run if search.module is enabled. A module
 * should check which of its items were modified or added since the last
 * run. It is advised that you implement a throttling mechanism which indexes
 * at most 'search_cron_limit' items per run (see example below).
 *
 * You should also be aware that indexing may take too long and be aborted if
 * there is a PHP time limit. That's why you should update your internal
 * bookkeeping multiple times per run, preferably after every item that
 * is indexed.
 *
 * Per item that needs to be indexed, you should call search_index() with
 * its content as a single HTML string. The search indexer will analyse the
 * HTML and use it to assign higher weights to important words (such as
 * titles). It will also check for links that point to nodes, and use them to
 * boost the ranking of the target nodes.
 *
 * @ingroup search
 */
function hook_update_index()
{
    $limit = (int) variable_get('search_cron_limit', 100);
    $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit);
    foreach ($result as $node) {
        $node = node_load($node->nid);
        // Save the changed time of the most recent indexed node, for the search
        // results half-life calculation.
        variable_set('node_cron_last', $node->changed);
        // Render the node.
        node_build_content($node, 'search_index');
        $node->rendered = drupal_render($node->content);
        $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
        // Fetch extra data normally not visible
        $extra = module_invoke_all('node_update_index', $node);
        foreach ($extra as $t) {
            $text .= $t;
        }
        // Update index
        search_index($node->nid, 'node', $text);
    }
}
Example #29
0
}
$callback_options = array(array('function' => 'system_get_files_database', 'return' => ''), &$modules, 'module');
httprl_queue_background_callback($callback_options);
// Execute requests.
httprl_send_request();
// Show first module after running system_get_files_database().
echo httprl_pr(current($modules));
?>


Get 2 results from 2 different queries at the hook_boot bootstrap level in D6.

<?php 
// Run 2 queries and get the result.
$x = db_result(db_query_range("SELECT filename FROM {system} ORDER BY filename ASC", 0, 1));
$y = db_result(db_query_range("SELECT filename FROM {system} ORDER BY filename DESC", 0, 1));
echo $x . "<br \\>\n" . $y . "<br \\>\n";
unset($x, $y);
// Bail out here if background callbacks are disabled.
if (!httprl_is_background_callback_capable()) {
    return FALSE;
}
// Run above 2 queries and get the result via a background callback.
$args = array(array('type' => 'function', 'call' => 'db_query_range', 'args' => array('SELECT filename FROM {system} ORDER BY filename ASC', 0, 1)), array('type' => 'function', 'call' => 'db_result', 'args' => array('last' => NULL), 'return' => &$x), array('type' => 'function', 'call' => 'db_query_range', 'args' => array('SELECT filename FROM {system} ORDER BY filename DESC', 0, 1)), array('type' => 'function', 'call' => 'db_result', 'args' => array('last' => NULL), 'return' => &$y));
$callback_options = array(array('return' => ''), &$args);
// Queue up the request.
httprl_queue_background_callback($callback_options);
// Execute request.
httprl_send_request();
// Echo what was returned.
echo httprl_pr($x, $y);
Example #30
0
/**
 * Enables Domain Access modules to fire cron hooks across all
 * active domains.
 *
 * Each module implementing this hook will have the function run
 * once per active domain record.  The global $_domain variable
 * will be set to the current $domain passed as an argument.
 *
 * This function is especially useful if you need to run node queries
 * that obey node access rules.
 *
 * Note that Domain Prefix and Domain Conf are activated by this hook.
 * That means each domain will have its tables and variables loaded before
 * your function fires.
 *
 * @param $domain
 *  The information for the current domain record, taken from {domain}.
 *
 * @ingroup domain_hooks
 */
function hook_domaincron($domain)
{
    // Run a node query.
    $result = db_query_range(db_rewrite_sql("SELECT n.nid FROM {node} n ORDER BY n.changed"), 0, 1);
    $node = db_fetch_object($result);
    // Set a variable for each domain containing the last node updated.
    variable_set('domain_' . $domain['domain_id'] . '_lastnode', $node->nid);
}