Example #1
0
function wiki_replace_link_callback($matches)
{
    if (count($matches) < 2) {
        return null;
    }
    if ($matches[1] == 'wiki') {
        $rev = Revisions::instance()->getTableName(true);
        $page = Wiki::instance()->getTableName(true);
        $where1 = 'WHERE page_id = ' . $matches[2] . ' AND project_id = ' . active_project()->getId();
        $where2 = 'WHERE id = ' . $matches[2] . ' AND project_id = ' . active_project()->getId();
        $sql = "SELECT page_id, name FROM {$rev} {$where1} ";
        $sql .= "AND revision = ( select revision from {$page} {$where2} )";
        //echo $sql;
        $row = DB::executeOne($sql);
        if (!count($row)) {
            return null;
        }
        $url = get_url($matches[1], 'view', array('id' => $matches[2]));
        $url = str_replace('&amp;', '&', $url);
        return '"' . $row['name'] . '(' . $row['page_id'] . ')":' . $url;
    }
    $user = Users::instance()->getTableName(true);
    $where1 = 'WHERE id = ' . $matches[2];
    $sql = "SELECT id, display_name FROM {$user} {$where1} ";
    echo $sql;
    $row = DB::executeOne($sql);
    if (!count($row)) {
        return null;
    }
    $url = get_url($matches[1], 'card', array('id' => $matches[2]));
    $url = str_replace('&amp;', '&', $url);
    return '"' . $row['display_name'] . '(' . $row['id'] . ')":' . $url;
}
 static function countPendingPreviousTasks($task_id)
 {
     $ids = array();
     // Build Main SQL
     $sql = "\r\n\t\tSELECT count(`previous_task_id`) AS row_count FROM `" . TABLE_PREFIX . "project_task_dependencies` AS ptd\r\n\t\tLEFT JOIN `" . TABLE_PREFIX . "project_tasks` AS e ON ptd.`previous_task_id` = e.`object_id`\r\n\t\tWHERE `task_id` = " . $task_id . " AND `e`.`completed_on` = " . DB::escape(EMPTY_DATETIME) . "\r\n\t\tAND 0 = (SELECT `trashed_by_id` FROM `" . TABLE_PREFIX . "objects` WHERE `id`=`previous_task_id`)\r\n\t\t\r\n\t\t";
     // Execute query and build the resultset
     $row = DB::executeOne($sql);
     return (int) array_var($row, 'row_count', 0);
 }
 static function typeAllowChilds($dimension_id, $parent_object_type_id)
 {
     if (isset(self::$allow_childs_cache[$dimension_id . "-" . $parent_object_type_id])) {
         return self::$allow_childs_cache[$dimension_id . "-" . $parent_object_type_id];
     }
     $sql = "SELECT count(*) as total FROM " . TABLE_PREFIX . "dimension_object_type_hierarchies \r\n  \t\t\tWHERE dimension_id = {$dimension_id} AND parent_object_type_id = {$parent_object_type_id} ";
     $res = DB::executeOne($sql);
     $allow = (bool) array_var($res, 'total');
     self::$allow_childs_cache[$dimension_id . "-" . $parent_object_type_id] = $allow;
     return $allow;
 }
 /**
  * Return default contact Address type
  *
  * @access public
  * @param Contact $contact
  * @return AddressType
  */
 function getContactMainAddressType(Contact $contact)
 {
     $contact_address_values_table = ContactAddresss::instance()->getTableName(true);
     $address_types_table = AddressTypes::instance()->getTableName(true);
     $sql = "SELECT {$address_types_table}.* FROM {$address_types_table}, {$contact_address_values_table} WHERE {$address_types_table}.`id` = {$contact_address_values_table}.`address_type_id` AND {$contact_address_values_table}.`is_main` = '1' AND {$contact_address_values_table}.`contact_id` = ?";
     $row = DB::executeOne($sql, $contact->getId());
     if (is_array($row)) {
         return ImTypes::instance()->loadFromRow($row);
     }
     // if
     return null;
 }
 /**
  * Return default contact IM type
  *
  * @access public
  * @param Contact $contact
  * @return ImType
  */
 function getDefaultContactImType(Contact $contact)
 {
     $contact_im_values_table = ContactImValues::instance()->getTableName(true);
     $im_types_table = ImTypes::instance()->getTableName(true);
     $sql = "SELECT {$im_types_table}.* FROM {$im_types_table}, {$contact_im_values_table} WHERE {$im_types_table}.`id` = {$contact_im_values_table}.`im_type_id` AND {$contact_im_values_table}.`is_default` = '1' AND {$contact_im_values_table}.`contact_id` = ?";
     $row = DB::executeOne($sql, $contact->getId());
     if (is_array($row)) {
         return ImTypes::instance()->loadFromRow($row);
     }
     // if
     return null;
 }
Example #6
0
/**
 * Contact member cache
 *
 */
function core_dimensions_update_7_8()
{
    //UPDATE depth for all members
    //update root members
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 1  WHERE parent_member_id = 0;");
    //clean root members
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 2  WHERE parent_member_id != 0 AND depth = 1;");
    $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE parent_member_id =0 ORDER BY id");
    $members_depth = array_flat($members_depth);
    $members_depth = implode(",", $members_depth);
    $depth = 2;
    $max_depth = DB::executeOne("SELECT  MAX(depth) AS depth FROM `" . TABLE_PREFIX . "members`");
    //update all depths
    for ($i = $depth; $i <= $max_depth['depth']; $i++) {
        //update members depth
        DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = " . $depth . " WHERE parent_member_id  IN (" . $members_depth . ");");
        //Get member from next depth
        $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE depth= " . $depth . " ORDER BY id");
        $members_depth = array_flat($members_depth);
        $members_depth = implode(",", $members_depth);
        $depth++;
    }
    //END UPDATE depth for all members
    //Load the contact member cache
    set_time_limit(0);
    ini_set('memory_limit', '512M');
    $users = Contacts::getAllUsers();
    $dimensions = Dimensions::findAll();
    $dimensions_ids = array();
    foreach ($dimensions as $dimension) {
        if ($dimension->getDefinesPermissions()) {
            $dimensions_ids[] = $dimension->getId();
        }
    }
    $dimensions_ids = implode(",", $dimensions_ids);
    $root_members = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id IN (" . $dimensions_ids . ") AND parent_member_id=0 ORDER BY id");
    foreach ($users as $user) {
        try {
            DB::beginWork();
            foreach ($root_members as $member) {
                ContactMemberCaches::updateContactMemberCache($user, $member['id'], $member['parent_member_id']);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }
    //END Load the contact member cache
}
 /**
 * Return main contact IM type
 *
 * @access public
 * @param Contact $contact
 * @return ImType
 */
 function getContactMainImType(Contact $contact) {
   
   $contact_im_values_table = ContactImValues::instance()->getTableName(true);
   $im_types_table = ImTypes::instance()->getTableName(true);
   
   $sql = "SELECT $im_types_table.* FROM $im_types_table, $contact_im_values_table WHERE $im_types_table.`id` = $contact_im_values_table.`im_type_id` AND $contact_im_values_table.`is_main` = '1' AND $contact_im_values_table.`contact_id` = ?";
   $row = DB::executeOne($sql, $contact->getId());
   if(is_array($row)) {
     return ImTypes::instance()->loadFromRow($row);
   } // if
   
   return null;
   
 } // getContactMainImType
Example #8
0
/**
 * Function for retrieving single lang value from database
 *
 * @access public
 * @param string $name
 * @return string
 */
function lang_from_db($name)
{
    global $language, $locale_id;
    static $langs;
    if (!is_array($langs)) {
        $langs = array();
    }
    if (!array_key_exists($name, $langs)) {
        if (!isset($language)) {
            $language = 'en_us';
        }
        if (!isset($locale_id)) {
            $language_country = explode('_', $language);
            $a = isset($language_country[0]) ? $language_country[0] : 'en';
            $b = isset($language_country[1]) ? $language_country[1] : 'us';
            $sql = "select `id` from `" . TABLE_PREFIX . "i18n_locales` where language_code = '{$a}' and country_code = '{$b}'";
            try {
                $result = DB::executeOne($sql);
                if ($result) {
                    $locale_id = $result['id'];
                }
            } catch (Exception $e) {
                $locale_id = 1;
            }
        }
        $langs[$name] = $name;
        $sql = "select `description` from `" . TABLE_PREFIX . "i18n_values` where `name` = '{$name}' and locale_id = '{$locale_id}'";
        try {
            $result = DB::executeOne($sql);
            if ($result) {
                $langs[$name] = $result['description'];
            } else {
                $category_id = 0;
                $sql = "insert into `" . TABLE_PREFIX . "i18n_values` (`locale_id`, `category_id`, `name`, `description`) values( '{$locale_id}', '{$category_id}', '{$name}', '~{$name}');";
                try {
                    mysql_query($sql);
                } catch (Exception $e) {
                }
            }
        } catch (Exception $e) {
        }
    }
    return $langs[$name];
}
/**
 * Function for retrieving single lang value from database
 *
 * @access public
 * @param string $name
 * @return string
 */
function lang_from_db($name)
{
    static $langs;
    if (!is_array($langs)) {
        $langs = array();
    }
    if (!array_key_exists($name, $langs)) {
        $langs[$name] = $name;
        $sql = "select `description` from `" . TABLE_PREFIX . "i18n_values` where `name` = '{$name}'";
        try {
            $result = DB::executeOne($sql);
            if ($result) {
                $langs[$name] = $result['description'];
            }
        } catch (Exception $e) {
        }
    }
    return $langs[$name];
}
Example #10
0
 /**
 * Load row from database based on ID
 *
 * @access public
 * @param mixed $id
 * @return array
 */
 function loadRow($id) {
   $cols = $this->getLoadColumns(true);
   $imploded = implode(', ', $cols);
   $sql = sprintf("SELECT %s FROM %s WHERE %s", 
     $imploded, 
     $this->getTableName(true), 
     $this->getConditionsById($id)
   ); // sprintf
   
   $cols = null;
   $imploded = null;
   
   return DB::executeOne($sql);
 } // loadRow
     }
     $cobj = null;
 }
 // add mails to sharing table for account owners
 if ($sql != "") {
     $sql .= " ON DUPLICATE KEY UPDATE group_id=group_id;";
     DB::execute($sql);
     $sql = "";
 }
 if (count($processed_objects) > 0) {
     $processed_objects_ids = "(" . implode("),(", $processed_objects) . ")";
     DB::execute("INSERT INTO " . TABLE_PREFIX . "processed_objects (object_id) VALUES {$processed_objects_ids} ON DUPLICATE KEY UPDATE object_id=object_id");
 }
 if (COMPLETE_MIGRATION_OUT != 'console') {
     $all = Objects::count();
     $row = DB::executeOne("SELECT COUNT(object_id) AS 'row_count' FROM " . TABLE_PREFIX . "processed_objects");
     $proc_count = $row['row_count'];
     if ($all <= $proc_count) {
         unset($_SESSION['hide_back_button']);
         $status_message = "Execution of 'Fill searchable objects and sharing table' completed.";
         foreach ($_SESSION['additional_steps'] as $k => $step) {
             if ($step['url'] == 'complete_migration.php') {
                 unset($_SESSION['additional_steps'][$k]);
             }
         }
     } else {
         if (!isset($_SESSION['additional_steps'])) {
             $_SESSION['additional_steps'] = array();
         }
         $add_step = true;
         foreach ($_SESSION['additional_steps'] as $step) {
Example #12
0
 /**
  * Return number of company users
  *
  * @access public
  * @param void
  * @return integer
  */
 function countUsers()
 {
     $users_table = Users::instance()->getTableName(true);
     $contacts_table = Contacts::instance()->getTableName(true);
     $escaped_pk = is_array($pk_columns = Companies::getPkColumns()) ? '*' : DB::escapeField($pk_columns);
     $users = array();
     $sql = "SELECT COUNT({$users_table}.{$escaped_pk}) AS 'row_count' FROM {$users_table}, {$contacts_table} WHERE ({$users_table}.`id` = {$contacts_table}.`user_id` AND {$contacts_table}.`company_id` = " . DB::escape($this->getId()) . " )";
     $row = DB::executeOne($sql);
     return (int) array_var($row, 'row_count', 0);
 }
 /**
  * Return mail address for the contact.
  *
  * @access public
  * @param void
  * @return string
  */
 function getEmailAddress($type = null)
 {
     $contact_id = $this->getId();
     $type_condition = $type ? "AND name = '{$type}'" : "";
     $sql = "SELECT * FROM " . TABLE_PREFIX . "contact_emails ce\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "email_types t\r\n\t\t\t\tON ce.email_type_id = t.id\r\n\t\t\t\tWHERE TRIM(email_address) <> ''\r\n\t\t\t\tAND email_address IS NOT NULL\r\n\t\t\t\tAND contact_id = {$contact_id}\r\n\t\t\t\t{$type_condition} order by is_main desc LIMIT 1";
     if ($row = DB::executeOne($sql)) {
         return $row['email_address'];
     }
     return null;
 }
/**
 * @param array of string $pluginNames
 */
static function executeInstaller($name) {
	
	$table_prefix = TABLE_PREFIX;
	tpl_assign('table_prefix', $table_prefix);
	
	$default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci';
	tpl_assign('default_charset', $default_charset);
	
	$default_collation = 'collate utf8_unicode_ci';
	tpl_assign('default_collation', $default_collation);
	
	$engine = DB_ENGINE;
	tpl_assign('engine', $engine);
		
	try {
		$path = ROOT . "/plugins/$name/info.php";
		if (file_exists ( $path )) {
			DB::beginWork ();
			$pluginInfo = include_once $path;
			
			//0. Check if exists in plg table
			$sql = "SELECT id FROM " . TABLE_PREFIX . "plugins WHERE name = '$name' ";
			$plg_obj = DB::executeOne($sql);
			if (! $plg_obj) {
				//1. Insert into PLUGIN TABLE
				$cols = "name, is_installed, is_activated, version";
				$values = "'$name', 1, 1 ,'".array_var ( $pluginInfo, 'version' )."'";
				if (is_numeric ( array_var ( $pluginInfo, 'id' ) )) {
					$cols = "id, " . $cols;
					$values = array_var ( $pluginInfo, 'id' ) . ", " . $values;
				}
				$sql = "INSERT INTO " . TABLE_PREFIX . "plugins ($cols) VALUES ($values) ON DUPLICATE KEY UPDATE name=name";
				DB::executeOne($sql);
				$id = DB::lastInsertId();
				$pluginInfo ['id'] = $id;
				
			} else {
				$id = $plg_obj['id'];
				$pluginInfo ['id'] = $id;
			}
			
			//2. IF Plugin defines types, INSERT INTO ITS TABLE
			if (count ( array_var ( $pluginInfo, 'types' ) )) {
				foreach ( $pluginInfo ['types'] as $k => $type ) {
					if (isset ( $type ['name'] )) {
						$sql = "
							INSERT INTO " . TABLE_PREFIX . "object_types (name, handler_class, table_name, type, icon, plugin_id)
							 	VALUES (
							 	'" . array_var ( $type, "name" ) . "', 
							 	'" . array_var ( $type, "handler_class" ) . "', 
							 	'" . array_var ( $type, "table_name" ) . "', 
							 	'" . array_var ( $type, "type" ) . "', 
							 	'" . array_var ( $type, "icon" ) . "', 
								$id
							) ON DUPLICATE KEY UPDATE name=name";
						
						DB::executeOne($sql);
						$last_id = DB::lastInsertId();
						$pluginInfo['types'][$k]['id'] = $last_id;
						$type['id'] = $last_id;
					}
				}
			}
			
			//2. IF Plugin defines tabs, INSERT INTO ITS TABLE
			if (count ( array_var ( $pluginInfo, 'tabs' ) )) {
				foreach ( $pluginInfo ['tabs'] as $k => $tab ) {
					if (isset ( $tab ['title'] )) {
						$type_id = array_var ( $type, "id" );
						$sql = "
							INSERT INTO " . TABLE_PREFIX . "tab_panels (
								id,
								title, 
								icon_cls, 
								refresh_on_context_change, 
								default_controller, 
								default_action, 
								initial_controller, 
								initial_action, 
								enabled, 
								type,  
								plugin_id, 
								object_type_id )
						 	VALUES (
						 		'" . array_var ( $tab, 'id' ) . "', 
						 		'" . array_var ( $tab, 'title' ) . "', 
						 		'" . array_var ( $tab, 'icon_cls' ) . "',
						 		'" . array_var ( $tab, 'refresh_on_context_change' ) . "',
						 		'" . array_var ( $tab, 'default_controller' ) . "',
						 		'" . array_var ( $tab, 'default_action' ) . "',
								'" . array_var ( $tab, 'initial_controller' ) . "',
								'" . array_var ( $tab, 'initial_action' ) . "',
								'" . array_var ( $tab, 'enabled', 1 ) . "',
								'" . array_var ( $tab, 'type' ) . "',
								$id,
								" . array_var ( $tab, 'object_type_id' ) . "
							) ON DUPLICATE KEY UPDATE name=name";
						
						DB::executeOne($sql);
						
						// INSERT INTO TAB PANEL PERMISSSION
						$sql = "
							INSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (
								permission_group_id,
								tab_panel_id 
							)
						 	VALUES ( 1,'" . array_var ( $tab, 'id' ) . "' ),  ( 2,'" . array_var ( $tab, 'id' ) . "' )  ON DUPLICATE KEY UPDATE permission_group_id = permission_group_id ";
						
						DB::executeOne($sql);
					}
				}
			}
			
			// Create schema sql query
			
			$schema_creation = ROOT . "/plugins/$name/install/sql/mysql_schema.php";
			if (file_exists ( $schema_creation )) {
				$total_queries = 0;
				$executed_queries = 0;
				executeMultipleQueries ( tpl_fetch ( $schema_creation ), $total_queries, $executed_queries );
				Logger::log("Schema created for plugin $name");
			}
			// Create schema sql query
			$schema_query = ROOT . "/plugins/$name/install/sql/mysql_initial_data.php";
			if (file_exists ( $schema_query )) {
				$total_queries = 0;
				$executed_queries = 0;
				executeMultipleQueries ( tpl_fetch ( $schema_query ), $total_queries, $executed_queries );
				Logger::log ( "Initial data loaded for plugin  '$name'." . mysql_error () );
			}
			
			$install_script = ROOT . "/plugins/$name/install/install.php";
			if (file_exists ( $install_script )) {
				include_once $install_script;
			}
			DB::commit ();
			return true;
		}
		
	} catch (Exception $e) {
		//echo $e->getMessage();
		DB::rollback();
		throw $e;
	}
	
	return false;
}
Example #15
0
 /**
  * This validator will return true if $value is unique (there is no row with such value in that field)
  *
  * @access public
  * @param string $field Filed name
  * @param mixed $value Value that need to be checked
  * @return boolean
  */
 function validateUniquenessOf()
 {
     // Don't do COUNT(*) if we have one PK column
     $escaped_pk = is_array($pk_columns = $this->getPkColumns()) ? '*' : DB::escapeField($pk_columns);
     // Get columns
     $columns = func_get_args();
     if (!is_array($columns) || count($columns) < 1) {
         return true;
     }
     // Check if we have existsing columns
     foreach ($columns as $column) {
         if (!$this->columnExists($column)) {
             return false;
         }
     }
     // foreach
     // Get where parets
     $where_parts = array();
     foreach ($columns as $column) {
         $where_parts[] = DB::escapeField($column) . ' = ' . DB::escape($this->getColumnValue($column));
     }
     // if
     // If we have new object we need to test if there is any other object
     // with this value. Else we need to check if there is any other EXCEPT
     // this one with that value
     if ($this->isNew()) {
         $sql = sprintf("SELECT COUNT({$escaped_pk}) AS 'row_count' FROM %s WHERE %s", $this->getTableName(true), implode(' AND ', $where_parts));
     } else {
         // Prepare PKs part...
         $pks = $this->getPkColumns();
         $pk_values = array();
         if (is_array($pks)) {
             foreach ($pks as $pk) {
                 $pk_values[] = sprintf('%s <> %s', DB::escapeField($pk), DB::escape($this->getColumnValue($pk)));
             }
             // foreach
         } else {
             $pk_values[] = sprintf('%s <> %s', DB::escapeField($pks), DB::escape($this->getColumnValue($pks)));
         }
         // if
         // Prepare SQL
         $sql = sprintf("SELECT COUNT({$escaped_pk}) AS 'row_count' FROM %s WHERE (%s) AND (%s)", $this->getTableName(true), implode(' AND ', $where_parts), implode(' AND ', $pk_values));
     }
     // if
     $row = DB::executeOne($sql);
     return array_var($row, 'row_count', 0) < 1;
 }
Example #16
0
 /**
  * Load row from database based on ID
  *
  * @access public
  * @param mixed $id
  * @return array
  */
 function loadRow($id)
 {
     trace(__FILE__, "loadRow({$id})");
     $sql = sprintf("SELECT %s FROM %s WHERE %s", implode(', ', $this->getLoadColumns(true)), $this->getTableName(true), $this->getConditionsById($id));
     // sprintf
     trace(__FILE__, "loadRow({$id}) sql={$sql}");
     return DB::executeOne($sql);
 }
Example #17
0
/**
 * Iused by installers (plugin installers) 
 */
function executeMultipleQueries($sql, &$total_queries = null , &$executed_queries = null ) {
	if(!trim($sql)) {
		$total_queries = 0;
		$executed_queries = 0;
	} // if

	// Make it work on PHP 5.0.4
	$sql = str_replace(array("\r\n", "\r"), array("\n", "\n"), $sql);

	$queries = explode(";\n", $sql);
	if(!is_array($queries) || !count($queries)) {
		$total_queries = 0;
		$executed_queries = 0;
	} 

	$total_queries = count($queries);
	foreach($queries as $query) {
		if(trim($query)) {
			DB::executeOne(trim($query));
			$executed_queries++;
		}
	}
}
Example #18
0
 /**
  * Returns number of objects tagged with specific tag
  *
  * @access public
  * @param string $tag Tag name
  * @param Project $project Only objects that belong to this project
  * @param boolean $exclude_private Exclude private objects from listing
  * @return integer
  */
 function countObjectsByTag($tag, $exclude_private = false)
 {
     if ($exclude_private) {
         $row = DB::executeOne("SELECT COUNT(`id`) AS 'row_count' FROM " . self::instance()->getTableName(true) . " WHERE `tag` = ? AND `is_private` = ?", $tag, 0);
     } else {
         $row = DB::executeOne("SELECT COUNT(`id`) AS 'row_count' FROM " . self::instance()->getTableName(true) . " WHERE `tag` = ?", $tag);
     }
     // if
     return array_var($row, 'row_count', 0);
 }
 static function addObjToSharingTable($oid, $tid, $obj_mem_ids)
 {
     $gids = array();
     $table_prefix = defined('FORCED_TABLE_PREFIX') && FORCED_TABLE_PREFIX ? FORCED_TABLE_PREFIX : TABLE_PREFIX;
     //1. clear sharing table for this object
     SharingTables::delete("object_id={$oid}");
     //2. get dimensions of this object's members that defines permissions
     $res = DB::execute("SELECT d.id as did FROM " . $table_prefix . "dimensions d INNER JOIN " . $table_prefix . "members m on m.dimension_id=d.id\r\n\t\t\t\tWHERE m.id IN ( SELECT member_id FROM " . $table_prefix . "object_members WHERE object_id = {$oid} AND is_optimization = 0 ) AND d.defines_permissions = 1");
     $dids_tmp = array();
     while ($row = $res->fetchRow()) {
         $dids_tmp[$row['did']] = $row['did'];
     }
     $res->free();
     $dids = array_values($dids_tmp);
     $dids_tmp = null;
     $sql_from = "" . $table_prefix . "contact_member_permissions cmp\r\n\t\tLEFT JOIN " . $table_prefix . "members m ON m.id = cmp.member_id\r\n\t\tLEFT JOIN " . $table_prefix . "dimensions d ON d.id = m.dimension_id";
     $member_where_conditions = "";
     $dim_where_conditions = "";
     // if users can add objects without classifying then check for permissions with member_id=0
     if (config_option('let_users_create_objects_in_root')) {
         $member_where_conditions = "member_id=0 OR ";
         $dim_where_conditions = " OR d.id IS NULL";
     }
     $sql_where = "({$member_where_conditions} member_id IN ( SELECT member_id FROM " . $table_prefix . "object_members WHERE object_id = {$oid} AND is_optimization = 0)) AND cmp.object_type_id = {$tid}";
     //3. If there are dimensions that defines permissions containing any of the object members
     if (count($dids)) {
         // 3.1 get permission groups with permissions over the object.
         $sql_fields = "permission_group_id  AS group_id";
         $sql = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t{$sql_fields}\r\n\t\t\t\tFROM\r\n\t\t\t\t{$sql_from}\r\n\t\t\t\tWHERE\r\n\t\t\t\t{$sql_where} AND (d.id IN (" . implode(',', $dids) . ") {$dim_where_conditions})\r\n\t\t\t";
         $res = DB::execute($sql);
         $gids_tmp = array();
         while ($row = $res->fetchRow()) {
             $gids_tmp[$row['group_id']] = $row['group_id'];
         }
         $res->free();
         // allow all permission groups
         $allow_all_rows = DB::executeAll("SELECT DISTINCT permission_group_id FROM " . $table_prefix . "contact_dimension_permissions cdp\r\n\t\t\t\t\tINNER JOIN " . $table_prefix . "members m on m.dimension_id=cdp.dimension_id\r\n\t\t\t\t\tWHERE cdp.permission_type='allow all' AND cdp.dimension_id IN (" . implode(',', $dids) . ");");
         if (is_array($allow_all_rows)) {
             foreach ($allow_all_rows as $row) {
                 $gids_tmp[$row['permission_group_id']] = $row['permission_group_id'];
             }
         }
         $gids = array_values($gids_tmp);
         $gids_tmp = null;
         // check for mandatory dimensions
         $enabled_dimensions_sql = "";
         $enabled_dimensions_ids = implode(',', config_option('enabled_dimensions'));
         if ($enabled_dimensions_ids != "") {
             $enabled_dimensions_sql = "AND id IN ({$enabled_dimensions_ids})";
         }
         $mandatory_dim_ids = Dimensions::findAll(array('id' => true, 'conditions' => "`defines_permissions`=1 {$enabled_dimensions_sql} AND `permission_query_method`='" . DIMENSION_PERMISSION_QUERY_METHOD_MANDATORY . "'"));
         if (count($gids) > 0 && count($mandatory_dim_ids) > 0) {
             $sql = "SELECT om.member_id, m.dimension_id FROM " . $table_prefix . "object_members om\r\n\t\t\t\t\tINNER JOIN " . $table_prefix . "members m ON m.id=om.member_id INNER JOIN " . $table_prefix . "dimensions d ON d.id=m.dimension_id\r\n\t\t\t\t\tWHERE om.object_id = {$oid} AND om.is_optimization = 0 AND d.id IN (" . implode(",", $mandatory_dim_ids) . ")";
             // Object members in mandatory dimensions
             $object_member_ids_res = DB::executeAll($sql);
             $mandatory_dim_members = array();
             if (!is_null($object_member_ids_res)) {
                 foreach ($object_member_ids_res as $row) {
                     if (!isset($mandatory_dim_members[$row['dimension_id']])) {
                         $mandatory_dim_members[$row['dimension_id']] = array();
                     }
                     $mandatory_dim_members[$row['dimension_id']][] = $row['member_id'];
                 }
                 $mandatory_dim_allowed_pgs = array();
                 // Check foreach group that it has permissions over at least one member of each mandatory dimension
                 foreach ($mandatory_dim_members as $mdim_id => $mmember_ids) {
                     $sql = "SELECT pg.id FROM " . $table_prefix . "permission_groups pg\r\n\t\t\t\t\t\t\tINNER JOIN " . $table_prefix . "contact_dimension_permissions cdp ON cdp.permission_group_id=pg.id\r\n\t\t\t\t\t\t\tINNER JOIN " . $table_prefix . "contact_member_permissions cmp ON cmp.permission_group_id=pg.id\r\n\t\t\t\t\t\t\tWHERE cdp.dimension_id = '{$mdim_id}' AND (\r\n\t\t\t\t\t\t\tcdp.permission_type='allow all' OR cdp.permission_type='check' AND cmp.permission_group_id IN (" . implode(',', $gids) . ")\r\n\t\t\t\t\t\t\tAND cmp.member_id IN (" . implode(',', $mmember_ids) . ")\r\n\t\t\t\t\t\t)";
                     $permission_groups_res = DB::executeAll($sql);
                     $mandatory_dim_allowed_pgs[$mdim_id] = array();
                     if (!is_null($permission_groups_res)) {
                         foreach ($permission_groups_res as $row) {
                             if (!in_array($row['id'], $mandatory_dim_allowed_pgs[$mdim_id])) {
                                 $mandatory_dim_allowed_pgs[$mdim_id][] = $row['id'];
                             }
                         }
                     }
                 }
                 if (isset($mandatory_dim_allowed_pgs) && count($mandatory_dim_allowed_pgs) > 0) {
                     $original_mandatory_dim_allowed_pgs = $mandatory_dim_allowed_pgs;
                     $allowed_gids = array_pop($mandatory_dim_allowed_pgs);
                     foreach ($mandatory_dim_allowed_pgs as $pg_array) {
                         $allowed_gids = array_intersect($allowed_gids, $pg_array);
                     }
                     // If an user has permissions in one dim using a group and in other dim using his personal permissions then add to sharing table its personal permission group
                     $pg_ids = array_unique(array_flat($original_mandatory_dim_allowed_pgs));
                     if (count($pg_ids) == 0) {
                         $pg_ids[0] = 0;
                     }
                     $contact_pgs = array();
                     $contact_pg_rows = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "contact_permission_groups WHERE permission_group_id IN (" . implode(',', $pg_ids) . ") ORDER BY permission_group_id");
                     if (is_array($contact_pg_rows)) {
                         foreach ($contact_pg_rows as $cpgr) {
                             if (!isset($contact_pgs[$cpgr['contact_id']])) {
                                 $contact_pgs[$cpgr['contact_id']] = array();
                             }
                             $contact_pgs[$cpgr['contact_id']][] = $cpgr['permission_group_id'];
                         }
                     }
                     // each user must have at least one pg for every dimension
                     foreach ($contact_pgs as $contact_id => $permission_groups) {
                         $has_one = array_flip(array_keys($original_mandatory_dim_allowed_pgs));
                         foreach ($has_one as $k => &$v) {
                             $v = false;
                         }
                         foreach ($permission_groups as $pg_id) {
                             foreach ($original_mandatory_dim_allowed_pgs as $dim_id => $allowedpgs) {
                                 if (in_array($pg_id, $allowedpgs)) {
                                     $has_one[$dim_id] = true;
                                     break;
                                 }
                             }
                         }
                         // all dims must be true in this array to allow permissions
                         $has_permission = !in_array(false, $has_one);
                         if ($has_permission) {
                             $contact_row = DB::executeOne("SELECT permission_group_id FROM " . TABLE_PREFIX . "contacts where object_id = {$contact_id}");
                             if (is_array($contact_row) && $contact_row['permission_group_id'] > 0) {
                                 $allowed_gids[] = $contact_row['permission_group_id'];
                             }
                         }
                     }
                     $gids = array_unique($allowed_gids, SORT_NUMERIC);
                 } else {
                     $gids = array();
                 }
             }
         }
     } else {
         if ($obj_mem_ids) {
             // 3.2 No memeber dimensions defines permissions.
             // No esta en ninguna dimension que defina permisos, El objecto esta en algun lado
             // => En todas las dimensiones en la que está no definen permisos => Busco todos los grupos
             $gids = PermissionGroups::instance()->findAll(array('id' => true, 'conditions' => "type != 'roles'"));
         } else {
             // if this object is an email and it is unclassified => add to sharing table the permission groups of the users that have permissions in the email's account
             if (Plugins::instance()->isActivePlugin('mail')) {
                 $mail_ot = ObjectTypes::instance()->findByName('mail');
                 if ($mail_ot instanceof ObjectType && $tid == $mail_ot->getId()) {
                     $gids = array_flat(DB::executeAll("\r\n\t\t\t\t\t\t\tSELECT cpg.permission_group_id\r\n\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "contact_permission_groups cpg\r\n\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "contacts c ON c.permission_group_id=cpg.permission_group_id\r\n\t\t\t\t\t\t\tWHERE cpg.contact_id IN (\r\n\t\t\t\t\t\t\t  SELECT mac.contact_id FROM " . TABLE_PREFIX . "mail_account_contacts mac WHERE mac.account_id = (SELECT mc.account_id FROM " . TABLE_PREFIX . "mail_contents mc WHERE mc.object_id={$oid})\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t"));
                 }
             }
         }
     }
     if (count($gids)) {
         $stManager = SharingTables::instance();
         $stManager->populateGroups($gids, $oid);
         $gids = null;
     }
 }
Example #20
0
 static function getTotalMinutesWorkedOnObject($object_id)
 {
     $sql = " SELECT SUM(GREATEST(TIMESTAMPDIFF(MINUTE,start_time,end_time),0)) - SUM(subtract/60) as total\r\n\t\t\t\tFROM `" . TABLE_PREFIX . "timeslots`\r\n\t\t\t\tWHERE `rel_object_id` =  " . $object_id . " \r\n\t\t\t\tAND `end_time` > " . DB::escape(EMPTY_DATETIME) . ";";
     return array_var(DB::executeOne($sql), "total");
 }
	/**
	 * @deprecated by listing(args) 
	 * @param unknown_type $context
	 * @param unknown_type $object_type
	 * @param unknown_type $order
	 * @param unknown_type $order_dir
	 * @param unknown_type $extra_conditions
	 * @param unknown_type $join_params
	 * @param unknown_type $trashed
	 * @param unknown_type $archived
	 * @param unknown_type $start
	 * @param unknown_type $limit
	 */
	static function getContentObjects($context, $object_type, $order=null, $order_dir=null, $extra_conditions=null, $join_params=null, $trashed=false, $archived=false, $start = 0 , $limit=null){
		$table_name = $object_type->getTableName();
		$object_type_id = $object_type->getId();
		
		//Join conditions
		$join_conditions = self::prepareJoinConditions($join_params);
		
    	//Trash && Archived conditions
    	$conditions = self::prepareTrashandArchivedConditions($trashed, $archived);
    	$trashed_cond = $conditions[0];
    	$archived_cond = $conditions[1];
    	
    	//Order conditions
    	$order_conditions = self::prepareOrderConditions($order, $order_dir);
    	
    	//Extra conditions
		if (!$extra_conditions) $extra_conditions = "";
		
		//Dimension conditions
    	$member_conditions = self::prepareDimensionConditions($context, $object_type_id);
    	if ($member_conditions == "") $member_conditions = "true";
    	
    	$limit_query = "";
    	if ($limit !== null) {
    		$limit_query = "LIMIT $start , $limit " ;
    	} 
    	
    	$sql_count = "SELECT COUNT( DISTINCT `om`.`object_id` ) AS total FROM `".TABLE_PREFIX."object_members` `om` 
    		INNER JOIN `".TABLE_PREFIX."objects` `o` ON `o`.`id` = `om`.`object_id`
    		INNER JOIN `".TABLE_PREFIX."$table_name` `e` ON `e`.`object_id` = `o`.`id`
    		$join_conditions WHERE $trashed_cond $archived_cond AND ($member_conditions) $extra_conditions";
    	$total = array_var(DB::executeOne($sql_count), "total");	
    		
    	$sql = "SELECT DISTINCT `om`.`object_id` FROM `".TABLE_PREFIX."object_members` `om` 
    		INNER JOIN `".TABLE_PREFIX."objects` `o` ON `o`.`id` = `om`.`object_id`
    		INNER JOIN `".TABLE_PREFIX."$table_name` `e` ON `e`.`object_id` = `o`.`id`
    		$join_conditions WHERE $trashed_cond $archived_cond AND ($member_conditions) $extra_conditions $order_conditions
    		$limit_query
    		";
		
	    $result = DB::execute($sql);
    	$rows = $result->fetchAll();
    	$objects = array();
    	$handler_class = $object_type->getHandlerClass();
    	if (!is_null($rows)) {
    		$ids = array();
	    	foreach ($rows as $row) {
	    		$ids[] = array_var($row, 'object_id');
	    	}
	    	if (count($ids) > 0) {
	    		$join_str = "";
	    		if ($join_params) {
	    			$join_str = ', "join" => array(';
	    			
		    		if (isset($join_params['join_type'])) $join_str .= '"join_type" => "'. $join_params['join_type']  .'",';
		    		if (isset($join_params['table'])) $join_str .= '"table" => "' . $join_params['table'] .'",';
		    		if (isset($join_params['jt_field'])) $join_str .= '"jt_field" => "' . $join_params['jt_field'] .'",';
		    		if (isset($join_params['e_field'])) $join_str .= '"e_field" => "' . $join_params['e_field'] .'",';
		    		if (isset($join_params['j_sub_q'])) $join_str .= '"j_sub_q" => "' . $join_params['j_sub_q'] .'",';
		    		if (str_ends_with($join_str, ",")) $join_str = substr($join_str, 0, strlen($join_str)-1);
		    		$join_str .= ')';
	    		}
	    		$phpCode = '$objects = '.$handler_class.'::findAll(array("conditions" => "`e`.`object_id` IN ('.implode(',', $ids).')", "order" => "'.str_replace("ORDER BY ", "", $order_conditions).'"'.$join_str.'));';
	    		eval($phpCode);
	    	}
    	}
    	

    	$result = new stdClass();
    	$result->objects = $objects ;
    	$result->total = $total ;
    	
    	return $result ;
	}
Example #22
0
 function getBillingTotal(User $user)
 {
     //$project_ids = $this->getAllSubWorkspacesQuery($user);
     $user_cond = '';
     if (isset($user_id)) {
         $user_cond = ' AND timeslots.user_id = ' . $user_id;
     }
     $row = DB::executeOne('SELECT SUM(timeslots.fixed_billing) as total_billing from ' . Timeslots::instance()->getTableName() . ' as timeslots, ' . ProjectTasks::instance()->getTableName() . ' as tasks WHERE ((' . ProjectTasks::getWorkspaceString($this->getId()) . ' AND timeslots.object_id = tasks.id AND timeslots.object_manager = \'ProjectTasks\')' . ' OR (timeslots.object_manager = \'Project\' AND timeslots.object_id = ' . $this->getId() . '))' . $user_cond);
     return array_var($row, 'total_billing', 0);
 }
Env::useHelper('format');
Env::useHelper('permissions');
define('SCRIPT_MEMORY_LIMIT', 1024 * 1024 * 1024);
// 1 GB
@set_time_limit(0);
ini_set('memory_limit', SCRIPT_MEMORY_LIMIT / (1024 * 1024) + 50 . 'M');
//UPDATE depth for all members
//update root members
DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 1  WHERE parent_member_id = 0;");
//clean root members
DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 2  WHERE parent_member_id != 0 AND depth = 1;");
$members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE parent_member_id =0 ORDER BY id");
$members_depth = array_flat($members_depth);
$members_depth = implode(",", $members_depth);
$depth = 2;
$max_depth = DB::executeOne("SELECT  MAX(depth) AS depth FROM `" . TABLE_PREFIX . "members`");
//update all depths
for ($i = $depth; $i <= $max_depth['depth']; $i++) {
    //update members depth
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = " . $depth . " WHERE parent_member_id  IN (" . $members_depth . ");");
    //Get member from next depth
    $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE depth= " . $depth . " ORDER BY id");
    $members_depth = array_flat($members_depth);
    $members_depth = implode(",", $members_depth);
    $depth++;
}
//END UPDATE depth for all members
echo "\nStart Truncate  contact_member_cache\n-----------------------------------------------------------------";
DB::execute("TRUNCATE TABLE " . TABLE_PREFIX . "contact_member_cache;");
echo "\nEnd Truncate  contact_member_cache\n-----------------------------------------------------------------";
$users = Contacts::getAllUsers();
 /**
  * Enter description here...
  *
  * @param Array $context: array of the selected dimensions and/or members
  * @deprecated use ContentDataObjects::listing() instead 
  */
 static function getObjectsFromContext($context, $order = null, $order_dir = null, $trashed = false, $archived = false, $filters = null, $start = 0, $limit = null, $obj_type_types = null)
 {
     //Filters conditions
     $filter_conditions = self::prepareFiltersConditions($filters);
     $name_filter_condition = $filter_conditions[0];
     $obj_ids_filter_condition = $filter_conditions[1];
     $type_filter_condition = $filter_conditions[2];
     //Trash && Archived conditions
     $conditions = self::prepareTrashandArchivedConditions($trashed, $archived);
     $trashed_cond = $conditions[0];
     $archived_cond = $conditions[1];
     //Order conditions
     $order_conditions = self::prepareOrderConditions($order, $order_dir);
     //Dimension conditions
     $member_conditions = self::prepareDimensionConditions($context);
     if ($member_conditions == "") {
         $member_conditions = "true";
     }
     $limit_query = "";
     if ($limit !== null && $start !== null) {
         $limit_query = "LIMIT {$start} , {$limit} ";
     }
     if ($obj_type_types == null) {
         $obj_type_types = array('content_object');
     }
     // $exists_member_cond: checks if the logged user deleted or archived the object then he always can see it in the trash can or archived objs panel
     $trashed_by_id_cond = $trashed ? "OR `o`.`trashed_by_id` = " . logged_user()->getId() : "";
     $archived_by_id_cond = $archived ? "OR `o`.`archived_by_id` = " . logged_user()->getId() : "";
     $exists_member_cond = "(NOT `om`.`member_id` IS NULL {$trashed_by_id_cond} {$archived_by_id_cond})";
     $sql_count = "SELECT count( DISTINCT `o`.`id` ) AS total FROM `" . TABLE_PREFIX . "objects` `o` \r\n\t\t\t\tINNER JOIN `" . TABLE_PREFIX . "object_types` `ot` ON `ot`.`id` = `o`.`object_type_id` \r\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "object_members` `om` ON `o`.`id` = `om`.`object_id` \r\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "project_tasks` `t` ON `t`.`object_id` = `o`.`id`\r\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "project_milestones` `m` ON `m`.`object_id` = `o`.`id`\r\n\t    \t\t\r\n\t\t\t\tWHERE {$trashed_cond} {$archived_cond}\r\n\t\t\t\tAND {$exists_member_cond}\r\n\t\t\t\tAND ( `t`.`is_template` IS NULL OR `t`.`is_template` = 0 )\r\n\t\t\t\tAND ( `m`.`is_template` IS NULL OR `m`.`is_template` = 0 )\r\n\t\t\t\tAND `ot`.`type` IN ('" . implode("','", $obj_type_types) . "')\r\n\t\t\t\tAND ({$member_conditions}) {$name_filter_condition} {$obj_ids_filter_condition} {$type_filter_condition} {$order_conditions}";
     $total = array_var(DB::executeOne($sql_count), "total");
     $sql = "SELECT DISTINCT `o`.`id` FROM `" . TABLE_PREFIX . "objects` `o` \r\n\t\t\t\tINNER JOIN `" . TABLE_PREFIX . "object_types` `ot` ON `ot`.`id` = `o`.`object_type_id`\r\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "object_members` `om` ON `o`.`id` = `om`.`object_id` \r\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "project_tasks` `t` ON `t`.`object_id` = `o`.`id`\r\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "project_milestones` `m` ON `m`.`object_id` = `o`.`id`\r\n\t    \t\t\r\n\t\t\t\tWHERE {$trashed_cond} {$archived_cond}\r\n\t\t\t\tAND {$exists_member_cond}\r\n\t\t\t\tAND ( `t`.`is_template` IS NULL OR `t`.`is_template` = 0 )\r\n\t\t\t\tAND ( `m`.`is_template` IS NULL OR `m`.`is_template` = 0 )\r\n\t\t\t\tAND `ot`.`type` IN ('" . implode("','", $obj_type_types) . "')\r\n\t\t\t\tAND ({$member_conditions}) {$name_filter_condition} {$obj_ids_filter_condition} {$type_filter_condition} {$order_conditions}\r\n\t\t\t\t{$limit_query} ";
     $result = DB::execute($sql);
     $rows = $result->fetchAll();
     $objects = array();
     if (!is_null($rows)) {
         $ids = array();
         foreach ($rows as $row) {
             $ids[] = array_var($row, 'id');
         }
         if (count($ids) > 0) {
             $q_order = "";
             if (!is_null($order)) {
                 if (!is_array($order)) {
                     $q_order = "`" . str_replace("o.", "", $order) . "` {$order_dir}";
                 } else {
                     $q_order = "";
                     foreach ($order as $o) {
                         $q_order .= ($q_order == "" ? "" : ", ") . "`" . str_replace("o.", "", $o) . "` {$order_dir}";
                     }
                 }
             }
             $query_params = array("conditions" => "`id` IN (" . implode(",", $ids) . ")");
             if (trim($q_order) != "") {
                 $query_params["order"] = $q_order;
             }
             $objects = Objects::findAll($query_params);
         }
     }
     $result = new stdClass();
     $result->objects = $objects;
     $result->total = $total;
     return $result;
 }
Example #25
0
	/**
	 * Return mail address for the contact.
	 *
	 * @access public
	 * @param void
	 * @return string
	 */
	 function getEmailAddress($type=null) {
	 	$contact_id = $this->getId();
	 	$type_condition =  ($type) ? "AND name = 'personal'" : "";
	 	
	 	$sql = "SELECT * FROM ".TABLE_PREFIX."contact_emails ce
				LEFT JOIN ".TABLE_PREFIX."email_types t
				ON ce.email_type_id = t.id
				WHERE TRIM(email_address) <> ''
				AND email_address IS NOT NULL
				AND contact_id = $contact_id
				$type_condition order by is_main desc LIMIT 1";
		if ($row = DB::executeOne($sql)) {
			return $row['email_address'];	
		}				
		return null;
	 } 
	function __construct() {
		$this->pagination = new StdClass();
		parent::__construct();
		prepare_company_website_controller($this, 'website');
		ajx_set_panel("search");
		self::$MYSQL_MIN_WORD_LENGHT = (int)array_var(DB::executeOne("SHOW variables LIKE 'ft_min_word_len' "),"Value");
	}
        function export_google_calendar() {
		ajx_current("empty");
                
                require_once 'Zend/Loader.php';

                Zend_Loader::loadClass('Zend_Gdata');
                Zend_Loader::loadClass('Zend_Gdata_AuthSub');
                Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
                Zend_Loader::loadClass('Zend_Gdata_Calendar');
                
                $users = ExternalCalendarUsers::findByContactId();
                if($users){
                    if($users->getSync() == 1){
                        $sql = "SELECT ec.* FROM `".TABLE_PREFIX."external_calendars` ec,`".TABLE_PREFIX."external_calendar_users` ecu 
                                WHERE ec.calendar_feng = 1 AND ecu.contact_id = ".logged_user()->getId();
                        $calendar_feng = DB::executeOne($sql);
                        $events = ProjectEvents::findNoSync();

                        $user = $users->getAuthUser();
                        $pass = $users->getAuthPass();
                        $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;

                        try
                        {
                                $client = Zend_Gdata_ClientLogin::getHttpClient($user,$pass,$service);  
                                $gdataCal = new Zend_Gdata_Calendar($client);

                                if ($calendar_feng){
                                    foreach ($events as $event){
                                        $calendarUrl = 'http://www.google.com/calendar/feeds/'.$calendar_feng['calendar_user'].'/private/full';

                                        $newEvent = $gdataCal->newEventEntry();
                                        $newEvent->title = $gdataCal->newTitle($event->getObjectName());
                                        $newEvent->content = $gdataCal->newContent($event->getDescription());

                                        $star_time = explode(" ",$event->getStart()->format("Y-m-d H:i:s"));
                                        $end_time = explode(" ",$event->getDuration()->format("Y-m-d H:i:s"));

                                        if($event->getTypeId() == 2){
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0];
                                            $when->endTime = $end_time[0];
                                            $newEvent->when = array($when);
                                        }else{                                    
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0]."T".$star_time[1].".000-00:00";
                                            $when->endTime = $end_time[0]."T".$end_time[1].".000-00:00";
                                            $newEvent->when = array($when);
                                        }

                                        // insert event
                                        $createdEvent = $gdataCal->insertEvent($newEvent, $calendarUrl);

                                        $event_id = explode("/",$createdEvent->id->text);
                                        $special_id = end($event_id); 
                                        $event->setSpecialID($special_id);
                                        $event->setUpdateSync(ProjectEvents::date_google_to_sql($createdEvent->updated));
                                        $event->setExtCalId($calendar_feng['id']);
                                        $event->save();
                                    }                             
                                }else{
                                    $appCalUrl = '';
                                    $calFeed = $gdataCal->getCalendarListFeed();        
                                    foreach ($calFeed as $calF){
                                        $instalation = explode("/", ROOT_URL);
                                        $instalation_name = end($instalation);
                                        if($calF->title->text == lang('feng calendar',$instalation_name)){
                                            $appCalUrl = $calF->content->src;
                                            $t_calendario = $calF->title->text;
                                        }
                                    }    

                                    if($appCalUrl != ""){
                                        $title_cal = $t_calendario;
                                    }else{
                                        $instalation = explode("/", ROOT_URL);
                                        $instalation_name = end($instalation);
                                        $appCal = $gdataCal -> newListEntry();
                                        $appCal -> title = $gdataCal-> newTitle(lang('feng calendar',$instalation_name));                         
                                        $own_cal = "http://www.google.com/calendar/feeds/default/owncalendars/full";                        
                                        $new_cal = $gdataCal->insertEvent($appCal, $own_cal);

                                        $title_cal = $new_cal->title->text;
                                        $appCalUrl = $new_cal->content->src;                                
                                    }               

                                    $cal_src = explode("/",$appCalUrl);
                                    array_pop($cal_src);
                                    $calendar_visibility = end($cal_src);
                                    array_pop($cal_src);
                                    $calendar_user = end($cal_src);                            

                                    $calendar = new ExternalCalendar();
                                    $calendar->setCalendarUser($calendar_user);
                                    $calendar->setCalendarVisibility($calendar_visibility);
                                    $calendar->setCalendarName($title_cal);
                                    $calendar->setExtCalUserId($users->getId());
                                    $calendar->setCalendarFeng(1);
                                    $calendar->save();

                                    foreach ($events as $event){                               
                                        $calendarUrl = 'http://www.google.com/calendar/feeds/'.$calendar->getCalendarUser().'/private/full';

                                        $newEvent = $gdataCal->newEventEntry();

                                        $newEvent->title = $gdataCal->newTitle($event->getObjectName());
                                        $newEvent->content = $gdataCal->newContent($event->getDescription());

                                        $star_time = explode(" ",$event->getStart()->format("Y-m-d H:i:s"));
                                        $end_time = explode(" ",$event->getDuration()->format("Y-m-d H:i:s"));

                                        if($event->getTypeId() == 2){
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0];
                                            $when->endTime = $end_time[0];
                                            $newEvent->when = array($when);
                                        }else{                                    
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0]."T".$star_time[1].".000-00:00";
                                            $when->endTime = $end_time[0]."T".$end_time[1].".000-00:00";
                                            $newEvent->when = array($when);
                                        }

                                        // insert event
                                        $createdEvent = $gdataCal->insertEvent($newEvent, $calendarUrl);

                                        $event_id = explode("/",$createdEvent->id->text);
                                        $special_id = end($event_id); 
                                        $event->setSpecialID($special_id);
                                        $event->setUpdateSync(ProjectEvents::date_google_to_sql($createdEvent->updated));
                                        $event->setExtCalId($calendar->getId());
                                        $event->save();
                                    } 
                                }
                                flash_success(lang('success add sync'));
                                ajx_current("reload");
                        }
                        catch(Exception $e)
                        {
                        		Logger::log($e->getMessage());
                                flash_error(lang('could not connect to calendar'));
                                ajx_current("empty");
                        }
                    }
                }
	}
 /**
  * Load row from database based on ID
  *
  * @access public
  * @param mixed $id
  * @return array
  */
 function loadRow($id)
 {
     $sql = sprintf("SELECT %s FROM %s WHERE %s", implode(', ', $this->getLoadColumns(true)), $this->getTableName(true), $this->getConditionsById($id));
     // sprintf
     return DB::executeOne($sql);
 }
 public static function countUnreadMailsInConversation($mail = null, $include_trashed = false)
 {
     if (!$mail instanceof MailContent || $mail->getConversationId() == 0) {
         return 0;
     }
     $conversation_id = $mail->getConversationId();
     $unread_cond = "AND NOT o.id IN \r\n\t\t( SELECT `rel_object_id` FROM `" . TABLE_PREFIX . "read_objects` `t` WHERE `contact_id` = " . logged_user()->getId() . " AND `t`.`is_read` = '1')";
     $deleted = ' AND `is_deleted` = false';
     if (!$include_trashed) {
         $deleted .= ' AND `trashed_by_id` = 0';
     }
     $sql = "\r\n\t\t\tSELECT count(o.id) AS total\r\n\t\t \tFROM " . TABLE_PREFIX . "mail_contents mc \r\n\t\t \tINNER JOIN " . TABLE_PREFIX . "objects o ON o.id = mc.object_id \r\n\t\t \tWHERE `conversation_id` = '{$conversation_id}' {$deleted} \r\n\t\t \tAND `account_id` = " . $mail->getAccountId() . " \r\n\t\t \tAND `state` <> 2 {$unread_cond}";
     $row = DB::executeOne($sql);
     //return 4 ;
     return $row['total'];
 }
 /**
  * @param array of string $pluginNames
  */
 static function executeInstaller($name)
 {
     $table_prefix = TABLE_PREFIX;
     tpl_assign('table_prefix', $table_prefix);
     $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci';
     tpl_assign('default_charset', $default_charset);
     $default_collation = 'collate utf8_unicode_ci';
     tpl_assign('default_collation', $default_collation);
     $engine = DB_ENGINE;
     tpl_assign('engine', $engine);
     try {
         $path = ROOT . "/plugins/{$name}/info.php";
         if (file_exists($path)) {
             DB::beginWork();
             $pluginInfo = (include_once $path);
             //0. Check if exists in plg table
             $sql = "SELECT id FROM " . TABLE_PREFIX . "plugins WHERE name = '{$name}' ";
             $plg_obj = DB::executeOne($sql);
             if (!$plg_obj) {
                 //1. Insert into PLUGIN TABLE
                 $cols = "name, is_installed, is_activated, version";
                 $values = "'{$name}', 1, 1 ,'" . array_var($pluginInfo, 'version') . "'";
                 if (is_numeric(array_var($pluginInfo, 'id'))) {
                     $cols = "id, " . $cols;
                     $values = array_var($pluginInfo, 'id') . ", " . $values;
                 }
                 $sql = "INSERT INTO " . TABLE_PREFIX . "plugins ({$cols}) VALUES ({$values}) ON DUPLICATE KEY UPDATE version='" . array_var($pluginInfo, 'version') . "'";
                 DB::executeOne($sql);
                 $id = DB::lastInsertId();
                 $pluginInfo['id'] = $id;
             } else {
                 $id = $plg_obj['id'];
                 $pluginInfo['id'] = $id;
             }
             if (isset($pluginInfo['dependences']) && is_array($pluginInfo['dependences'])) {
                 foreach ($pluginInfo['dependences'] as $dep_plugin_name) {
                     if (!Plugins::instance()->isActivePlugin($dep_plugin_name)) {
                         throw new Exception("To install this plugin you need to install '{$dep_plugin_name}' first.");
                     }
                 }
             }
             //2. IF Plugin defines types, INSERT INTO ITS TABLE
             if (count(array_var($pluginInfo, 'types'))) {
                 foreach ($pluginInfo['types'] as $k => $type) {
                     if (isset($type['name'])) {
                         $sql = "\r\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "object_types (name, handler_class, table_name, type, icon, plugin_id)\r\n\t\t\t\t\t\t\t \tVALUES (\r\n\t\t\t\t\t\t\t \t'" . array_var($type, "name") . "', \r\n\t\t\t\t\t\t\t \t'" . array_var($type, "handler_class") . "', \r\n\t\t\t\t\t\t\t \t'" . array_var($type, "table_name") . "', \r\n\t\t\t\t\t\t\t \t'" . array_var($type, "type") . "', \r\n\t\t\t\t\t\t\t \t'" . array_var($type, "icon") . "', \r\n\t\t\t\t\t\t\t\t{$id}\r\n\t\t\t\t\t\t\t) ON DUPLICATE KEY UPDATE name=name";
                         DB::executeOne($sql);
                         $last_id = DB::lastInsertId();
                         $pluginInfo['types'][$k]['id'] = $last_id;
                         $type['id'] = $last_id;
                     }
                 }
             }
             //2. IF Plugin defines tabs, INSERT INTO ITS TABLE
             if (count(array_var($pluginInfo, 'tabs'))) {
                 foreach ($pluginInfo['tabs'] as $k => $tab) {
                     if (isset($tab['title'])) {
                         $type_id = array_var($type, "id");
                         $sql = "\r\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "tab_panels (\r\n\t\t\t\t\t\t\t\tid,\r\n\t\t\t\t\t\t\t\ttitle, \r\n\t\t\t\t\t\t\t\ticon_cls, \r\n\t\t\t\t\t\t\t\trefresh_on_context_change, \r\n\t\t\t\t\t\t\t\tdefault_controller, \r\n\t\t\t\t\t\t\t\tdefault_action, \r\n\t\t\t\t\t\t\t\tinitial_controller, \r\n\t\t\t\t\t\t\t\tinitial_action, \r\n\t\t\t\t\t\t\t\tenabled, \r\n\t\t\t\t\t\t\t\ttype,  \r\n\t\t\t\t\t\t\t\tplugin_id, \r\n\t\t\t\t\t\t\t\tobject_type_id )\r\n\t\t\t\t\t\t \tVALUES (\r\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'id') . "', \r\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'title') . "', \r\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'icon_cls') . "',\r\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'refresh_on_context_change') . "',\r\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_controller') . "',\r\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_action') . "',\r\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_controller') . "',\r\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_action') . "',\r\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'enabled', 1) . "',\r\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'type') . "',\r\n\t\t\t\t\t\t\t\t{$id},\r\n\t\t\t\t\t\t\t\t" . array_var($tab, 'object_type_id') . "\r\n\t\t\t\t\t\t\t) ON DUPLICATE KEY UPDATE \r\n\t\t\t\t\t\t\t\tid = VALUES(`id`), \r\n\t\t\t\t\t\t\t\ttitle = VALUES(`title`), \r\n\t\t\t\t\t\t\t\ticon_cls = VALUES(`icon_cls`), \r\n\t\t\t\t\t\t\t\trefresh_on_context_change = VALUES(`refresh_on_context_change`), \r\n\t\t\t\t\t\t\t\tdefault_controller = VALUES(`default_controller`), \r\n\t\t\t\t\t\t\t\tdefault_action = VALUES(`default_action`), \r\n\t\t\t\t\t\t\t\tinitial_controller = VALUES(`initial_controller`), \r\n\t\t\t\t\t\t\t\tinitial_action = VALUES(`initial_action`), \r\n\t\t\t\t\t\t\t\tenabled = VALUES(`enabled`), \r\n\t\t\t\t\t\t\t\ttype = VALUES(`type`), \r\n\t\t\t\t\t\t\t\tplugin_id = VALUES(`plugin_id`),\r\n\t\t\t\t\t\t\t\tobject_type_id = VALUES(`object_type_id`);\r\n\t\t\t\t\t\t\t";
                         DB::executeOne($sql);
                         // INSERT INTO TAB PANEL PERMISSSION
                         $sql = "\r\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (\r\n\t\t\t\t\t\t\t\tpermission_group_id,\r\n\t\t\t\t\t\t\t\ttab_panel_id \r\n\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t \tVALUES ( 1,'" . array_var($tab, 'id') . "' ),  ( 2,'" . array_var($tab, 'id') . "' )  ON DUPLICATE KEY UPDATE permission_group_id = permission_group_id ";
                         DB::executeOne($sql);
                     }
                 }
             }
             // Create schema sql query
             $schema_creation = ROOT . "/plugins/{$name}/install/sql/mysql_schema.php";
             if (file_exists($schema_creation)) {
                 $total_queries = 0;
                 $executed_queries = 0;
                 executeMultipleQueries(tpl_fetch($schema_creation), $total_queries, $executed_queries);
                 Logger::log("Schema created for plugin {$name}");
             }
             // Create schema sql query
             $schema_query = ROOT . "/plugins/{$name}/install/sql/mysql_initial_data.php";
             if (file_exists($schema_query)) {
                 $total_queries = 0;
                 $executed_queries = 0;
                 executeMultipleQueries(tpl_fetch($schema_query), $total_queries, $executed_queries);
                 Logger::log("Initial data loaded for plugin  '{$name}'." . mysql_error());
             }
             $install_script = ROOT . "/plugins/{$name}/install/install.php";
             if (file_exists($install_script)) {
                 include_once $install_script;
             }
             DB::commit();
             return true;
         }
     } catch (Exception $e) {
         //echo $e->getMessage();
         DB::rollback();
         throw $e;
     }
     return false;
 }