List all the namespaces and plugins (Octobercms) - plugins

I am new to octobercms, I want to list all the existing namespaces and plugins and models in my project, how can I do it?

public function test_stat()
{
if(is_dir(('./plugins/'))){
$pluginPath = './plugins/' ;
$namespaces_list = [];
$namespaces = scandir($pluginPath);
foreach ($namespaces as $namespace){
if(!in_array($namespace, ['.', '..'])){
$plugins = scandir($pluginPath . $namespace);
if(count($plugins)>2){
$plugins = array_values($plugins);
$plugins_list = [];
foreach ($plugins as $plugin){
if(!in_array($plugin, ['.', '..'])){
if(is_dir($pluginPath . $namespace . '/' . $plugin . '/models')){
$modelsPath = $pluginPath . $namespace . '/' . $plugin . '/models';
$models = scandir($modelsPath);
$models_list = [];
foreach ($models as $model){
if(is_dir($modelsPath . '/' . $model) && !in_array($model, ['.', '..'])){
if(file_exists($modelsPath . '/' . $model . '/columns.yaml')){
$models_list[] = $model;
}
}
}
if(count($models_list) > 0){
$pluginNamespace = $namespace . '_' . $plugin;
$tables = DB::select("SHOW TABLES LIKE '" . $pluginNamespace . "%'");
$plugins_list[] = [
"name" => $plugin,
"models" => $models_list,
"tables" => $tables
];
}
}
}
}
$namespace_obj = NULL;
if(count($plugins_list) > 0){
$namespace_obj = [
"name" => $namespace,
"plugins" => $plugins_list
];
}
if($namespace_obj !== NULL){
$namespaces_list[] = $namespace_obj;
}
}
}
}
dump( $namespaces_list );
}else{
echo "";
return false;
}
die('<br>test<br>');
}

https://secure.php.net/manual/en/function.get-declared-classes.php
echo dump(get_declared_classes());
or
dd(get_declared_classes());

Related

Magento2: how to get the SKUs from the serialized condition in cart price rules

I need to get the SKUs from cart price rule to assign a specific attribute to them, but the condition is saved in the database serialized, and I want to make foreach loop to extract all the SKU's from the serialized condition :
?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objrules = $obj->create('Magento\SalesRule\Model\RuleFactory')->create();
$rules = $objrules->getCollection()->addFieldToFilter("is_active", "1");
foreach ($rules as $rule) {
echo $rule->getConditionsSerialized() . "\n";
}
and the result of the serialized condition is:
{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Combine","attribute":null,"operator":null,"value":1,"is_value_processed":null,"aggregator":"all","conditions":[{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product\\Subselect","attribute":"qty","operator":">=","value":"1","is_value_processed":null,"aggregator":"any","conditions":[{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817069","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817051","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817561","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817579","is_value_processed":false,"attribute_scope":null}]}]}
so, how can we extract all the SKU's from this condition.
thanks in advance.
try something like this:
<?php
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objrules = $obj->create('Magento\SalesRule\Model\RuleFactory')->create();
$rules = $objrules->getCollection()->addFieldToFilter("is_active", "1");
$skus = [];
if ($rules) {
foreach ($rules as $rule) {
$ruleData = $rule->getConditionsSerialized();
if ($ruleData) {
$ruleDataArray = json_decode($ruleData, true);
if (isset($ruleDataArray['conditions'])) {
$conditions = $ruleDataArray['conditions'];
foreach ($conditions as $condition) {
if (isset($condition['conditions'])) {
$productConditions = $condition['conditions'];
foreach ($productConditions as $productCondition) {
if (isset($productCondition['value'])) {
$skuValues = $productCondition['value'];
$skuValues = explode(",",$skuValues);
foreach ($skuValues as $skuValue) {
$skus[] = $skuValue;
}
}
}
}
}
}
}
}
}
$uniqSkus = array_unique($skus);
print_r($uniqSkus);
exit;

SuiteCRM add custom where condition in view.popup.php?

How to add custom where condition in view.popup.php ?
Someone suggests me to add custom where condition in view.list.php but my problem is, view.popup.php not calling the view.list.php so there is no meaning to add a custom condition in view.list.php.
Or is this possible to link custom view.popup.php to custom view.list.php ?
Following is long code because most of the code is the default and you will need to change where and select parts according to your need. I have used "Meeting" module for ilustration.
File path: custom\modules\\CustomMeeting.php
<?php
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
require_once("modules/Meetings/Meeting.php");
class CustomMeeting extends Meeting
{
/**
* * constructor
* */
public function __construct()
{
parent::Meeting();
}
/**
* Return the list query used by the list views and export button. Next generation of create_new_list_query function.
*
* Override this function to return a custom query.
*
* #param string $order_by custom order by clause
* #param string $where custom where clause
* #param array $filter Optioanal
* #param array $params Optional *
* #param int $show_deleted Optional, default 0, show deleted records is set to 1.
* #param string $join_type
* #param boolean $return_array Optional, default false, response as array
* #param object $parentbean creating a subquery for this bean.
* #param boolean $singleSelect Optional, default false.
* #return String select query string, optionally an array value will be returned if $return_array= true.
*/
function create_new_list_query($order_by, $where, $filter = array(), $params = array(), $show_deleted = 0, $join_type = '', $return_array = false, $parentbean = null, $singleSelect = false, $ifListForExport = false)
{
$GLOBALS['log']->fatal(print_r($_REQUEST, 1));
global $beanFiles, $beanList;
$selectedFields = array();
$secondarySelectedFields = array();
$ret_array = array();
$distinct = '';
if ($this->bean_implements('ACL') && ACLController::requireOwner($this->module_dir, 'list')) {
global $current_user;
$owner_where = $this->getOwnerWhere($current_user->id);
if (empty($where)) {
$where = $owner_where;
} else {
$where .= ' AND ' . $owner_where;
}
}
/* BEGIN - SECURITY GROUPS */
global $current_user, $sugar_config;
if ($this->module_dir == 'Users' && !is_admin($current_user) && isset($sugar_config['securitysuite_filter_user_list']) && $sugar_config['securitysuite_filter_user_list'] == true
) {
require_once('modules/SecurityGroups/SecurityGroup.php');
global $current_user;
$group_where = SecurityGroup::getGroupUsersWhere($current_user->id);
//$group_where = "user_name = 'admin'";
if (empty($where)) {
$where = " (" . $group_where . ") ";
} else {
$where .= " AND (" . $group_where . ") ";
}
} else
if ($this->bean_implements('ACL') && ACLController::requireSecurityGroup($this->module_dir, 'list')) {
require_once('modules/SecurityGroups/SecurityGroup.php');
global $current_user;
$owner_where = $this->getOwnerWhere($current_user->id);
$group_where = SecurityGroup::getGroupWhere($this->table_name, $this->module_dir, $current_user->id);
if (!empty($owner_where)) {
if (empty($where)) {
$where = " (" . $owner_where . " or " . $group_where . ") ";
} else {
$where .= " AND (" . $owner_where . " or " . $group_where . ") ";
}
} else {
$where .= ' AND ' . $group_where;
}
}
/* END - SECURITY GROUPS */
if (!empty($params['distinct'])) {
$distinct = ' DISTINCT ';
}
if (empty($filter)) {
$ret_array['select'] = " SELECT $distinct $this->table_name.* ";
} else {
$ret_array['select'] = " SELECT $distinct $this->table_name.id ";
}
$ret_array['from'] = " FROM $this->table_name ";
$ret_array['from_min'] = $ret_array['from'];
$ret_array['secondary_from'] = $ret_array['from'];
$ret_array['where'] = '';
$ret_array['order_by'] = '';
//secondary selects are selects that need to be run after the primary query to retrieve additional info on main
if ($singleSelect) {
$ret_array['secondary_select'] = & $ret_array['select'];
$ret_array['secondary_from'] = & $ret_array['from'];
} else {
$ret_array['secondary_select'] = '';
}
$custom_join = $this->getCustomJoin(empty($filter) ? true : $filter );
if ((!isset($params['include_custom_fields']) || $params['include_custom_fields'])) {
$ret_array['select'] .= $custom_join['select'];
}
$ret_array['from'] .= $custom_join['join'];
// Bug 52490 - Captivea (Sve) - To be able to add custom fields inside where clause in a subpanel
$ret_array['from_min'] .= $custom_join['join'];
$jtcount = 0;
//LOOP AROUND FOR FIXIN VARDEF ISSUES
require('include/VarDefHandler/listvardefoverride.php');
if (file_exists('custom/include/VarDefHandler/listvardefoverride.php')) {
require('custom/include/VarDefHandler/listvardefoverride.php');
}
$joined_tables = array();
if (!empty($params['joined_tables'])) {
foreach ($params['joined_tables'] as $table) {
$joined_tables[$table] = 1;
}
}
if (!empty($filter)) {
$filterKeys = array_keys($filter);
if (is_numeric($filterKeys[0])) {
$fields = array();
foreach ($filter as $field) {
$field = strtolower($field);
//remove out id field so we don't duplicate it
if ($field == 'id' && !empty($filter)) {
continue;
}
if (isset($this->field_defs[$field])) {
$fields[$field] = $this->field_defs[$field];
} else {
$fields[$field] = array('force_exists' => true);
}
}
} else {
$fields = $filter;
}
} else {
$fields = $this->field_defs;
}
$used_join_key = array();
//walk through the fields and for every relationship field add their relationship_info field
//relationshipfield-aliases are resolved in SugarBean::create_new_list_query through their relationship_info field
$addrelate = array();
foreach ($fields as $field => $value) {
if (isset($this->field_defs[$field]) && isset($this->field_defs[$field]['source']) &&
$this->field_defs[$field]['source'] == 'non-db') {
$addrelatefield = $this->get_relationship_field($field);
if ($addrelatefield)
$addrelate[$addrelatefield] = true;
}
if (!empty($this->field_defs[$field]['id_name'])) {
$addrelate[$this->field_defs[$field]['id_name']] = true;
}
}
$fields = array_merge($addrelate, $fields);
foreach ($fields as $field => $value) {
//alias is used to alias field names
$alias = '';
if (isset($value['alias'])) {
$alias = ' as ' . $value['alias'] . ' ';
}
if (empty($this->field_defs[$field]) || !empty($value['force_blank'])) {
if (!empty($filter) && isset($filter[$field]['force_exists']) && $filter[$field]['force_exists']) {
if (isset($filter[$field]['force_default']))
$ret_array['select'] .= ", {$filter[$field]['force_default']} $field ";
else
//spaces are a fix for length issue problem with unions. The union only returns the maximum number of characters from the first select statement.
$ret_array['select'] .= ", ' ' $field ";
}
continue;
}
else {
$data = $this->field_defs[$field];
}
//ignore fields that are a part of the collection and a field has been removed as a result of
//layout customization.. this happens in subpanel customizations, use case, from the contacts subpanel
//in opportunities module remove the contact_role/opportunity_role field.
if (isset($data['relationship_fields']) and ! empty($data['relationship_fields'])) {
$process_field = false;
foreach ($data['relationship_fields'] as $field_name) {
if (isset($fields[$field_name])) {
$process_field = true;
break;
}
}
if (!$process_field)
continue;
}
if ((!isset($data['source']) || $data['source'] == 'db') && (!empty($alias) || !empty($filter) )) {
$ret_array['select'] .= ", $this->table_name.$field $alias";
$selectedFields["$this->table_name.$field"] = true;
} else if ((!isset($data['source']) || $data['source'] == 'custom_fields') && (!empty($alias) || !empty($filter) )) {
//add this column only if it has NOT already been added to select statement string
$colPos = strpos($ret_array['select'], "$this->table_name" . "_cstm" . ".$field");
if (!$colPos || $colPos < 0) {
$ret_array['select'] .= ", $this->table_name" . "_cstm" . ".$field $alias";
}
$selectedFields["$this->table_name.$field"] = true;
}
if ($data['type'] != 'relate' && isset($data['db_concat_fields'])) {
$ret_array['select'] .= ", " . $this->db->concat($this->table_name, $data['db_concat_fields']) . " as $field";
$selectedFields[$this->db->concat($this->table_name, $data['db_concat_fields'])] = true;
}
//Custom relate field or relate fields built in module builder which have no link field associated.
if ($data['type'] == 'relate' && (isset($data['custom_module']) || isset($data['ext2']))) {
$joinTableAlias = 'jt' . $jtcount;
$relateJoinInfo = $this->custom_fields->getRelateJoin($data, $joinTableAlias, false);
$ret_array['select'] .= $relateJoinInfo['select'];
$ret_array['from'] .= $relateJoinInfo['from'];
//Replace any references to the relationship in the where clause with the new alias
//If the link isn't set, assume that search used the local table for the field
$searchTable = isset($data['link']) ? $relateJoinInfo['rel_table'] : $this->table_name;
$field_name = $relateJoinInfo['rel_table'] . '.' . !empty($data['name']) ? $data['name'] : 'name';
$where = preg_replace('/(^|[\s(])' . $field_name . '/', '${1}' . $relateJoinInfo['name_field'], $where);
$jtcount++;
}
//Parent Field
if ($data['type'] == 'parent') {
//See if we need to join anything by inspecting the where clause
$match = preg_match('/(^|[\s(])parent_(\w+)_(\w+)\.name/', $where, $matches);
if ($match) {
$joinTableAlias = 'jt' . $jtcount;
$joinModule = $matches[2];
$joinTable = $matches[3];
$localTable = $this->table_name;
if (!empty($data['custom_module'])) {
$localTable .= '_cstm';
}
global $beanFiles, $beanList, $module;
require_once($beanFiles[$beanList[$joinModule]]);
$rel_mod = new $beanList[$joinModule]();
$nameField = "$joinTableAlias.name";
if (isset($rel_mod->field_defs['name'])) {
$name_field_def = $rel_mod->field_defs['name'];
if (isset($name_field_def['db_concat_fields'])) {
$nameField = $this->db->concat($joinTableAlias, $name_field_def['db_concat_fields']);
}
}
$ret_array['select'] .= ", $nameField {$data['name']} ";
$ret_array['from'] .= " LEFT JOIN $joinTable $joinTableAlias
ON $localTable.{$data['id_name']} = $joinTableAlias.id";
//Replace any references to the relationship in the where clause with the new alias
$where = preg_replace('/(^|[\s(])parent_' . $joinModule . '_' . $joinTable . '\.name/', '${1}' . $nameField, $where);
$jtcount++;
}
}
if ($this->is_relate_field($field)) {
$this->load_relationship($data['link']);
if (!empty($this->$data['link'])) {
$params = array();
if (empty($join_type)) {
$params['join_type'] = ' LEFT JOIN ';
} else {
$params['join_type'] = $join_type;
}
if (isset($data['join_name'])) {
$params['join_table_alias'] = $data['join_name'];
} else {
$params['join_table_alias'] = 'jt' . $jtcount;
}
if (isset($data['join_link_name'])) {
$params['join_table_link_alias'] = $data['join_link_name'];
} else {
$params['join_table_link_alias'] = 'jtl' . $jtcount;
}
$join_primary = !isset($data['join_primary']) || $data['join_primary'];
$join = $this->$data['link']->getJoin($params, true);
$used_join_key[] = $join['rel_key'];
$rel_module = $this->$data['link']->getRelatedModuleName();
$table_joined = !empty($joined_tables[$params['join_table_alias']]) || (!empty($joined_tables[$params['join_table_link_alias']]) && isset($data['link_type']) && $data['link_type'] == 'relationship_info');
//if rname is set to 'name', and bean files exist, then check if field should be a concatenated name
global $beanFiles, $beanList;
// °3/21/2014 FIX NS-TEAM - Relationship fields could not be displayed in subpanels
//if($data['rname'] && !empty($beanFiles[$beanList[$rel_module]])) {
if (isset($data['rname']) && $data['rname'] == 'name' && !empty($beanFiles[$beanList[$rel_module]])) {
//create an instance of the related bean
require_once($beanFiles[$beanList[$rel_module]]);
$rel_mod = new $beanList[$rel_module]();
//if bean has first and last name fields, then name should be concatenated
if (isset($rel_mod->field_name_map['first_name']) && isset($rel_mod->field_name_map['last_name'])) {
$data['db_concat_fields'] = array(0 => 'first_name', 1 => 'last_name');
}
}
if ($join['type'] == 'many-to-many') {
if (empty($ret_array['secondary_select'])) {
$ret_array['secondary_select'] = " SELECT $this->table_name.id ref_id ";
if (!empty($beanFiles[$beanList[$rel_module]]) && $join_primary) {
require_once($beanFiles[$beanList[$rel_module]]);
$rel_mod = new $beanList[$rel_module]();
if (isset($rel_mod->field_defs['assigned_user_id'])) {
$ret_array['secondary_select'].= " , " . $params['join_table_alias'] . ".assigned_user_id {$field}_owner, '$rel_module' {$field}_mod";
} else {
if (isset($rel_mod->field_defs['created_by'])) {
$ret_array['secondary_select'].= " , " . $params['join_table_alias'] . ".created_by {$field}_owner , '$rel_module' {$field}_mod";
}
}
}
}
if (isset($data['db_concat_fields'])) {
$ret_array['secondary_select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
} else {
if (!isset($data['relationship_fields'])) {
$ret_array['secondary_select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
}
}
if (!$singleSelect) {
$ret_array['select'] .= ", ' ' $field ";
}
$count_used = 0;
foreach ($used_join_key as $used_key) {
if ($used_key == $join['rel_key'])
$count_used++;
}
if ($count_used <= 1) {//27416, the $ret_array['secondary_select'] should always generate, regardless the dbtype
// add rel_key only if it was not aready added
if (!$singleSelect) {
$ret_array['select'] .= ", ' ' " . $join['rel_key'] . ' ';
}
$ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'] . '.' . $join['rel_key'] . ' ' . $join['rel_key'];
}
if (isset($data['relationship_fields'])) {
foreach ($data['relationship_fields'] as $r_name => $alias_name) {
if (!empty($secondarySelectedFields[$alias_name]))
continue;
$ret_array['secondary_select'] .= ', ' . $params['join_table_link_alias'] . '.' . $r_name . ' ' . $alias_name;
$secondarySelectedFields[$alias_name] = true;
}
}
if (!$table_joined) {
$ret_array['secondary_from'] .= ' ' . $join['join'] . ' AND ' . $params['join_table_alias'] . '.deleted=0';
if (isset($data['link_type']) && $data['link_type'] == 'relationship_info' && ($parentbean instanceOf SugarBean)) {
$ret_array['secondary_where'] = $params['join_table_link_alias'] . '.' . $join['rel_key'] . "='" . $parentbean->id . "'";
}
}
} else {
if (isset($data['db_concat_fields'])) {
$ret_array['select'] .= ' , ' . $this->db->concat($params['join_table_alias'], $data['db_concat_fields']) . ' ' . $field;
} else {
$ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $data['rname'] . ' ' . $field;
}
if (isset($data['additionalFields'])) {
foreach ($data['additionalFields'] as $k => $v) {
if (!empty($data['id_name']) && $data['id_name'] == $v && !empty($fields[$data['id_name']])) {
continue;
}
$ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.' . $k . ' ' . $v;
}
}
if (!$table_joined) {
$ret_array['from'] .= ' ' . $join['join'] . ' AND ' . $params['join_table_alias'] . '.deleted=0';
if (!empty($beanList[$rel_module]) && !empty($beanFiles[$beanList[$rel_module]])) {
require_once($beanFiles[$beanList[$rel_module]]);
$rel_mod = new $beanList[$rel_module]();
if (isset($value['target_record_key']) && !empty($filter)) {
$selectedFields[$this->table_name . '.' . $value['target_record_key']] = true;
$ret_array['select'] .= " , $this->table_name.{$value['target_record_key']} ";
}
if (isset($rel_mod->field_defs['assigned_user_id'])) {
$ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.assigned_user_id ' . $field . '_owner';
} else {
$ret_array['select'] .= ' , ' . $params['join_table_alias'] . '.created_by ' . $field . '_owner';
}
$ret_array['select'] .= " , '" . $rel_module . "' " . $field . '_mod';
}
}
}
// To fix SOAP stuff where we are trying to retrieve all the accounts data where accounts.id = ..
// and this code changes accounts to jt4 as there is a self join with the accounts table.
//Martin fix #27494
if (isset($data['db_concat_fields'])) {
$buildWhere = false;
if (in_array('first_name', $data['db_concat_fields']) && in_array('last_name', $data['db_concat_fields'])) {
$exp = '/\(\s*?' . $data['name'] . '.*?\%\'\s*?\)/';
if (preg_match($exp, $where, $matches)) {
$search_expression = $matches[0];
//Create three search conditions - first + last, first, last
$first_name_search = str_replace($data['name'], $params['join_table_alias'] . '.first_name', $search_expression);
$last_name_search = str_replace($data['name'], $params['join_table_alias'] . '.last_name', $search_expression);
$full_name_search = str_replace($data['name'], $this->db->concat($params['join_table_alias'], $data['db_concat_fields']), $search_expression);
$buildWhere = true;
$where = str_replace($search_expression, '(' . $full_name_search . ' OR ' . $first_name_search . ' OR ' . $last_name_search . ')', $where);
}
}
if (!$buildWhere) {
$db_field = $this->db->concat($params['join_table_alias'], $data['db_concat_fields']);
$where = preg_replace('/' . $data['name'] . '/', $db_field, $where);
// For relationship fields replace their alias by the corresponsding link table and r_name
if (isset($data['relationship_fields']))
foreach ($data['relationship_fields'] as $r_name => $alias_name) {
$db_field = $this->db->concat($params['join_table_link_alias'], $r_name);
$where = preg_replace('/' . $alias_name . '/', $db_field, $where);
}
}
} else {
$where = preg_replace('/(^|[\s(])' . $data['name'] . '/', '${1}' . $params['join_table_alias'] . '.' . $data['rname'], $where);
// For relationship fields replace their alias by the corresponsding link table and r_name
if (isset($data['relationship_fields']))
foreach ($data['relationship_fields'] as $r_name => $alias_name)
$where = preg_replace('/(^|[\s(])' . $alias_name . '/', '${1}' . $params['join_table_link_alias'] . '.' . $r_name, $where);
}
if (!$table_joined) {
$joined_tables[$params['join_table_alias']] = 1;
$joined_tables[$params['join_table_link_alias']] = 1;
}
$jtcount++;
}
}
}
if (!empty($filter)) {
if (isset($this->field_defs['assigned_user_id']) && empty($selectedFields[$this->table_name . '.assigned_user_id'])) {
$ret_array['select'] .= ", $this->table_name.assigned_user_id ";
} else if (isset($this->field_defs['created_by']) && empty($selectedFields[$this->table_name . '.created_by'])) {
$ret_array['select'] .= ", $this->table_name.created_by ";
}
if (isset($this->field_defs['system_id']) && empty($selectedFields[$this->table_name . '.system_id'])) {
$ret_array['select'] .= ", $this->table_name.system_id ";
}
}
$where_auto = '1=1';
if ($show_deleted == 0) {
$where_auto = "$this->table_name.deleted=0";
} else if ($show_deleted == 1) {
$where_auto = "$this->table_name.deleted=1";
}
if ($where != "")
$ret_array['where'] = " where ($where) AND $where_auto";
else
$ret_array['where'] = " where $where_auto";
//make call to process the order by clause
$order_by = $this->process_order_by($order_by);
if (!empty($order_by)) {
$ret_array['order_by'] = " ORDER BY " . $order_by;
}
if ($singleSelect) {
unset($ret_array['secondary_where']);
unset($ret_array['secondary_from']);
unset($ret_array['secondary_select']);
}
if (<your check goes here>) {
$ret_array['from'] = $ret_array['from'] . " your sql to fetch data ";
$ret_array['where'] .=" AND meetings.id NOT IN (some condition)";
}
if ($return_array) {
return $ret_array;
}
return $ret_array['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
}
}

Notification.php for Windows Azure notification hub API using PHP

I want to send the notification, using windows azure notification hub api in PHP.
You have to interface directly with REST (http://msdn.microsoft.com/en-us/library/dn495827.aspx).
The code you will have to write is basically this one:
class Notification {
public $format;
public $payload;
# array with keynames for headers
# Note: Some headers are mandatory: Windows: X-WNS-Type, WindowsPhone: X-NotificationType
# Note: For Apple you can set Expiry with header: ServiceBusNotification-ApnsExpiry in W3C DTF, YYYY-MM-DDThh:mmTZD (for example, 1997-07-16T19:20+01:00).
public $headers;
function __construct($format, $payload) {
if (!in_array($format, ["template", "apple", "windows", "gcm", "windowsphone"])) {
throw new Exception('Invalid format: ' . $format);
}
$this->format = $format;
$this->payload = $payload;
}
}
class NotificationHub {
const API_VERSION = "?api-version=2013-10";
private $endpoint;
private $hubPath;
private $sasKeyName;
private $sasKeyValue;
function __construct($connectionString, $hubPath) {
$this->hubPath = $hubPath;
$this->parseConnectionString($connectionString);
}
private function parseConnectionString($connectionString) {
$parts = explode(";", $connectionString);
if (sizeof($parts) != 3) {
throw new Exception("Error parsing connection string: " . $connectionString);
}
foreach ($parts as $part) {
if (strpos($part, "Endpoint") === 0) {
$this->endpoint = "https" . substr($part, 11);
} else if (strpos($part, "SharedAccessKeyName") === 0) {
$this->sasKeyName = substr($part, 20);
} else if (strpos($part, "SharedAccessKey") === 0) {
$this->sasKeyValue = substr($part, 16);
}
}
}
private function generateSasToken($uri) {
$targetUri = strtolower(rawurlencode(strtolower($uri)));
$expires = time();
$expiresInMins = 60;
$expires = $expires + $expiresInMins * 60;
$toSign = $targetUri . "\n" . $expires;
$signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, $this->sasKeyValue, TRUE)));
$token = "SharedAccessSignature sr=" . $targetUri . "&sig="
. $signature . "&se=" . $expires . "&skn=" . $this->sasKeyName;
return $token;
}
public function broadcastNotification($notification) {
$this->sendNotification($notification, "");
}
public function sendNotification($notification, $tagsOrTagExpression) {
if (is_array($tagsOrTagExpression)) {
$tagExpression = implode(" || ", $tagsOrTagExpression);
} else {
$tagExpression = $tagsOrTagExpression;
}
# build uri
$uri = $this->endpoint . $this->hubPath . "/messages" . NotificationHub::API_VERSION;
$ch = curl_init($uri);
if (in_array($notification->format, ["template", "apple", "gcm"])) {
$contentType = "application/json";
} else {
$contentType = "application/xml";
}
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '.$token,
'Content-Type: '.$contentType,
'ServiceBusNotification-Format: '.$notification->format
];
if ("" !== $tagExpression) {
$headers[] = 'ServiceBusNotification-Tags: '.$tagExpression;
}
# add headers for other platforms
if (is_array($notification->headers)) {
$headers = array_merge($headers, $notification->headers);
}
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $notification->payload
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
if ($info['http_code'] <> 201) {
throw new Exception('Error sending notificaiton: '. $info['http_code'] . ' msg: ' . $response);
}
}
}
And use it this way: initialize your Notification Hubs client (substitute the connection string and hub name as instructed in the Get started tutorial):
$hub = new NotificationHub("connection string", "hubname");
Then add the send code depending on your target mobile platform.
Windows Store and Windows Phone 8.1 (non-Silverlight)
$toast = '<toast><visual><binding template="ToastText01"><text id="1">Hello from PHP!</text></binding></visual></toast>';
$notification = new Notification("windows", $toast);
$notification->headers[] = 'X-WNS-Type: wns/toast';
$hub->sendNotification($notification);
iOS
$alert = '{"aps":{"alert":"Hello from PHP!"}}';
$notification = new Notification("apple", $alert);
$hub->sendNotification($notification);
Android
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("gcm", $message);
$hub->sendNotification($notification);
Windows Phone 8.0 and 8.1 Silverlight
$toast = '<?xml version="1.0" encoding="utf-8"?>' .
'<wp:Notification xmlns:wp="WPNotification">' .
'<wp:Toast>' .
'<wp:Text1>Hello from PHP!</wp:Text1>' .
'</wp:Toast> ' .
'</wp:Notification>';
$notification = new Notification("mpns", $toast);
$notification->headers[] = 'X-WindowsPhone-Target : toast';
$notification->headers[] = 'X-NotificationClass : 2';
$hub->sendNotification($notification);
Kindle Fire
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("adm", $message);
$hub->sendNotification($notification);
For registration management you have to follow the content formats shown in the MSDN topic linked above, and probably do some nasty xml parsing... Be warned that element order is important and things will not work if the element are out of order.

How to create a category and add an image programatically

I've written a script that creates a category and adds a thumbnail image. It is inserted in the database but the thumbnail is not displayed.
When I upload from the backend it works fine.
This is my code.
<?php
require_once 'businessclasses.php';
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(1); // Mage_Core_Model_App::ADMIN_STORE_ID
$count = 0;
importRootCategories('us', '1/31/32', 4);
function importRootCategories($language, $path, $storeID)
{
$data = new getCSV();
$rows = $data->getRootCategories(); // Gets the list of root categories.
foreach($rows as $row) {
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row[$language])))); // Name of Category
if($language == "us") {
if($row[$language] == "")
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row["en"])))); // Name of Category
}
// Create category object
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeID); // 'US-Store' store is assigned to this category
$rootCategory['name'] = $categoryName;
$rootCategory['path'] = $path; // this is the catgeory path - 1 for root category
$rootCategory['display_mode'] = "PRODUCTS";
$rootCategory['include_in_menu'] = 1;
$rootCategory['is_active'] = 1;
$rootCategory['is_anchor'] = 1;
$rootCategory['thumbnail'] = _getCategoryImageFile($row['catimg'].'.jpg');
$category->addData($rootCategory);
try {
$category->save();
echo $rootCategoryId = $category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
}
}
function _getCategoryImageFile($filename)
{
$filePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS . $filename;
$fileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'import/category/'. $filename;
$imageUrl=file_get_contents($imageUrl);
$file_handler=fopen($filePath,'w');
if(fwrite($file_handler,$fileUrl)==false){
Mage::log('ERROR: ', null,'error');
}
else{
Mage::log('Image Created Successfully', null, '');
}
fclose($file_handler);
return $filename;
}
?>

How to get my zend script picture filename into a hidden field

OK, I am stumped here. I'm using a Zend script that helps me to upload pictures. It works great, but I am trying to capture the pictures name into a hidden field for a form. I'd like to note that the name changes, so I'd need to get whichever it ends up being put into the hidden field. Here is the Zend script:
<?php
if (isset($_POST['upload'])) {
require_once('scripts/library.php');
try {
$destination = 'xxxxxxxx';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '90kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
if (!$uploader->isValid()) {
$messages = $uploader->getMessages();
} else {
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$uploaded .= " and renamed $no_spaces";
}
$messages[] = "$uploaded";
}
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Here I am trying to make the $pic variable not to throw an error for now (on the form page)
if (isset($_POST['upload'])) { } else { $pic = "unknown";}
The $pic variable is what I was trying to have the filename from the zend script copied into. Any feedback is greaaaatly appreciated :)